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.
This commit is contained in:
Wenzel Jakob
2018-07-17 16:56:26 +02:00
committed by GitHub
parent b4719a60d3
commit cbd16a8247
6 changed files with 43 additions and 13 deletions

View File

@@ -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_SUBMODULE(stl, m) {
// 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);
}