Fix application of keep_alive policy to constructors (regression)
diff --git a/tests/test_call_policies.cpp b/tests/test_call_policies.cpp
index 65e54a0..8642188 100644
--- a/tests/test_call_policies.cpp
+++ b/tests/test_call_policies.cpp
@@ -32,7 +32,7 @@
TEST_SUBMODULE(call_policies, m) {
// Parent/Child are used in:
// test_keep_alive_argument, test_keep_alive_return_value, test_alive_gc_derived,
- // test_alive_gc_multi_derived, test_return_none
+ // test_alive_gc_multi_derived, test_return_none, test_keep_alive_constructor
class Child {
public:
Child() { py::print("Allocating child."); }
@@ -51,6 +51,7 @@
};
py::class_<Parent>(m, "Parent")
.def(py::init<>())
+ .def(py::init([](Child *) { return new Parent(); }), py::keep_alive<1, 2>())
.def("addChild", &Parent::addChild)
.def("addChildKeepAlive", &Parent::addChild, py::keep_alive<1, 2>())
.def("returnChild", &Parent::returnChild)
diff --git a/tests/test_call_policies.py b/tests/test_call_policies.py
index 6c60f81..7c83559 100644
--- a/tests/test_call_policies.py
+++ b/tests/test_call_policies.py
@@ -156,6 +156,25 @@
assert capture == "Releasing parent."
+def test_keep_alive_constructor(capture):
+ n_inst = ConstructorStats.detail_reg_inst()
+
+ with capture:
+ p = m.Parent(m.Child())
+ assert ConstructorStats.detail_reg_inst() == n_inst + 2
+ assert capture == """
+ Allocating child.
+ Allocating parent.
+ """
+ with capture:
+ del p
+ assert ConstructorStats.detail_reg_inst() == n_inst
+ assert capture == """
+ Releasing parent.
+ Releasing child.
+ """
+
+
def test_call_guard():
assert m.unguarded_call() == "unguarded"
assert m.guarded_call() == "guarded"