Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: memory leak in cpp_function (#3228) #3229

Merged
merged 8 commits into from
Aug 31, 2021
2 changes: 1 addition & 1 deletion include/pybind11/pybind11.h
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ class cpp_function : public function {
#endif
// UB without std::launder, but without breaking ABI and/or
// a significant refactoring it's "impossible" to solve.
if (!std::is_trivially_destructible<Func>::value)
if (!std::is_trivially_destructible<capture>::value)
rec->free_data = [](function_record *r) {
auto data = PYBIND11_STD_LAUNDER((capture *) &r->data);
(void) data;
Expand Down
29 changes: 29 additions & 0 deletions tests/test_embed/test_interpreter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -323,3 +323,32 @@ TEST_CASE("sys.argv gets initialized properly") {
}
py::initialize_interpreter();
}

class Counter {
public:
Counter() { cnt_++; }
Counter(const Counter &) { cnt_++; }
Counter(Counter &&) { cnt_++; }
yuantailing marked this conversation as resolved.
Show resolved Hide resolved
~Counter() { cnt_--; }
static int get_cnt() { return cnt_; }
Skylion007 marked this conversation as resolved.
Show resolved Hide resolved
void operator()() { }

private:
static int cnt_;
};

int Counter::cnt_ = 0;

// Related issue: https://github.com/pybind/pybind11/issues/3228
// Related PR: https://github.com/pybind/pybind11/pull/3229
TEST_CASE("Check objects are deconstructed in cpp_function") {
Counter counter;
{
py::cpp_function func(counter);
}
CHECK(Counter::get_cnt() == 1);
{
py::cpp_function func(std::move(counter));
}
CHECK(Counter::get_cnt() == 1);
}