stl.h: propagate return value policies to type-specific casters (#1455)
* stl.h: propagate return value policies to type-specific casters
Return value policies for containers like those handled in in 'stl.h'
are currently broken.
The problem is that detail::return_value_policy_override<C>::policy()
always returns 'move' when given a non-pointer/reference type, e.g.
'std::vector<...>'.
This is sensible behavior for custom types that are exposed via
'py::class_<>', but it does not make sense for types that are handled by
other type casters (STL containers, Eigen matrices, etc.).
This commit changes the behavior so that
detail::return_value_policy_override only becomes active when the type
caster derives from type_caster_generic.
Furthermore, the override logic is called recursively in STL type
casters to enable key/value-specific behavior.
diff --git a/tests/test_stl.cpp b/tests/test_stl.cpp
index 7d53e9c..cd0985d 100644
--- a/tests/test_stl.cpp
+++ b/tests/test_stl.cpp
@@ -8,6 +8,7 @@
*/
#include "pybind11_tests.h"
+#include "constructor_stats.h"
#include <pybind11/stl.h>
// Test with `std::variant` in C++17 mode, or with `boost::variant` in C++11/14
@@ -235,4 +236,21 @@
// test_stl_pass_by_pointer
m.def("stl_pass_by_pointer", [](std::vector<int>* v) { return *v; }, "v"_a=nullptr);
+
+ class Placeholder {
+ public:
+ Placeholder() { print_created(this); }
+ Placeholder(const Placeholder &) = delete;
+ ~Placeholder() { print_destroyed(this); }
+ };
+ py::class_<Placeholder>(m, "Placeholder");
+
+ /// test_stl_vector_ownership
+ m.def("test_stl_ownership",
+ []() {
+ std::vector<Placeholder *> result;
+ result.push_back(new Placeholder());
+ return result;
+ },
+ py::return_value_policy::take_ownership);
}