Skip to content

function<Type*(void)> will attempt to copy Type on return #1041

@gratzdhg

Description

@gratzdhg

Firstly, thank you for this wonderful library. As I was using it I found some unexpected/undesired behaviour. Wrapped function objects from std::functional will copy the result even when the result is of type pointer.
Here is my sample code to reproduce the issue.

#include <functional>
#include <pybind11/pybind11.h>
#include <pybind11/functional.h>

namespace py = pybind11;

struct Test {
    Test() {};
    Test(const Test &obj) = delete;
    int i;
};
Test* fullFunction()
{
    return new Test();
}
std::function<Test*(void)> func = &fullFunction;

PYBIND11_MODULE(example, m) {
    // optional module docstring
    m.attr("full") = py::cpp_function(func);
    m.attr("func") = func;
    py::class_<Test>(m,"Test")
        .def_readwrite("i",&Test::i);
}
import example
example.full()
example.func()

example.func() will result in an error: return_value_policy = copy, but the object is non-copyable!

It's my understanding that both full & func should return a Test* and that the underlying Test will not be copied however when the pybind11/functional wrapper handles it, it will attempt to copy Test*. I believe this occurs because a function object is an object and not a pointer which causes copy to be the default behaviour that is detected. Sorry if I have misunderstood anything.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions