问题
I've been using the excellent pybind11 library but have hit a brick wall. I need to return to Python a pointer to a non-copyable object (as the object contains unique_ptrs).
Generally this works fine with caveat of using return_value_policy::reference. However, returning a pointer to an object that has vector of non-copyable's results in a compilation error. It seems pybind wants to perform a copy in this case even though the return value policy is reference and the function explicitly returns a pointer.
Why is this and is there a workaround?
I am using VS2017 15.9.2 with the latest pybind11 off master
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <vector>
#include <memory>
/* This fails to compile... */
struct myclass
{
std::vector<std::unique_ptr<int>> numbers;
};
/* ...but this works
struct myclass
{
std::unique_ptr<int> number;
};
*/
void test(py::module &m)
{
py::class_<myclass> pymy(m, "myclass");
pymy.def_static("make", []() {
myclass *m = new myclass;
return m;
}, py::return_value_policy::reference);
}
回答1:
I worked this out
The copy constructor and assignment operator need to be explicitly deleted, i.e. adding the following allows pybind to recognise it cannot make a copy
myclass() = default;
myclass(const myclass &m) = delete;
myclass & operator= (const myclass &) = delete;
来源:https://stackoverflow.com/questions/53807248/pybind11-returning-a-pointer-to-a-container-of-unique-ptr