Closed
Description
Required prerequisites
- Make sure you've read the documentation. Your issue may be addressed there.
- Search the issue tracker and Discussions to verify that this hasn't already been reported. +1 or comment there if it has.
- Consider asking first in the Gitter chat room or in a Discussion.
Problem description
When constructing a pybind11::cpp_function
object with lvalue reference of a closure, the captures are copied but not to be deconstructed. The expected behavior is that all copies of captures are deconstructed.
Versions:
- python 3.8
- pybind11-2.7.1
- x86_64-linux-gnu-gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
The issue may be related to #1510 and pytorch/pytorch#5161.
Reproducible example code
Add the following code to https://github.com/pybind/python_example/blob/master/src/main.cpp
class A {
public:
A() { printf("A()\n"); }
A(A const &) { printf("A(A const &)\n"); }
A(A &&) { printf("A(A &&)\n"); }
~A() { printf("~A()\n"); }
};
m.def("foo1", [] {
A a;
auto bar = [a] { };
return py::cpp_function(bar);
});
m.def("foo2", [] {
A a;
auto bar = [a] { };
return py::cpp_function(std::move(bar));
});
Then call m.foo1()
. It shows that one object of A
is not deconstructed:
A()
A(A const &)
A(A const &)
~A()
~A()
Note that m.foo2()
does not cause memory leak:
A()
A(A const &)
A(A &&)
~A()
~A()
~A()