Skip to content

Add test case for memory leak when using lambdas #1301

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

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions tests/test_embed/test_interpreter.cpp
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#include <pybind11/embed.h>
#include <pybind11/functional.h>

#ifdef _MSC_VER
// Silence MSVC C++17 deprecation warning from Catch regarding std::uncaught_exceptions (up to catch
Expand All @@ -13,6 +14,7 @@
#include <thread>
#include <utility>


namespace py = pybind11;
using namespace py::literals;

Expand Down Expand Up @@ -302,6 +304,47 @@ TEST_CASE("Reload module from file") {
REQUIRE(result == 2);
}

class TestObject {
public:
TestObject(std::function<void()> f) : _id(++_count), _f(std::move(f)) {}

~TestObject() {
--_count;
py::print("~TestObject(" + std::to_string(_id) + ")");
}
int GetCount() const { return _id; }

static int _count;
int _id;
std::function<void()> _f;
};

int TestObject::_count = 0;

PYBIND11_EMBEDDED_MODULE(test_memory_leak, m) {
py::class_<TestObject, std::shared_ptr<TestObject>>(m, "TestObject")
.def(py::init<std::function<void()>>())
.def_property_readonly("count", &TestObject::GetCount);
}

TEST_CASE("Test that C++ objects are properly deconstructed.") {
{
auto local = py::dict();
local["__builtins__"] = py::globals()["__builtins__"];
py::exec(R"(
from test_memory_leak import TestObject

guard = TestObject(lambda: None)
)", local, local);
REQUIRE(1 == TestObject::_count);
local.clear();
}

py::finalize_interpreter();
REQUIRE(0 == TestObject::_count);
py::initialize_interpreter();
}

TEST_CASE("sys.argv gets initialized properly") {
py::finalize_interpreter();
{
Expand Down