Skip to content

[BUG]: Constructing pybind11::cpp_function with a closure causes memory leak #3228

Closed
@yuantailing

Description

@yuantailing

Required prerequisites

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()

Metadata

Metadata

Assignees

No one assigned

    Labels

    triageNew bug, unverified

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions