Skip to content

std::function<void(Foo &)> reports error when Foo is non-copyable and non-movable #1123

@qianyizh

Description

@qianyizh

This might be related to #765 and #1041

My problem is that I have a non-copyable and non-movable class Foo that I want to change in a callback function.

The C++ code is:

struct Foo {
	int a = 0;
	Foo() = default;
	Foo(const Foo &) = delete;
	Foo &operator=(const Foo &) = delete;
	Foo(Foo &&o) = delete;
	Foo &operator=(Foo &&o) = delete;
};

py::class_<Foo> foo(m, "Foo");
foo.def_readwrite("a", &Foo::a);
m.def("test_foo", [](std::function<void(Foo &)> f) {
	Foo x;
	f(x);
	return x.a;
});

The python code is:

def test_obj():
    def change_value(x):
        x.a = 1
    assert m.test_foo(change_value) == 1

This gives an error:

RuntimeError: return_value_policy = copy, but the object is non-copyable!

The real problem is that I want to change the return policy of std::function<void(Foo &)> f to return_policy_type::reference but it does not seem possible.

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