File tree 3 files changed +38
-1
lines changed
3 files changed +38
-1
lines changed Original file line number Diff line number Diff line change @@ -1134,6 +1134,7 @@ class class_ : public detail::generic_type {
1134
1134
} catch (const std::bad_weak_ptr &) {
1135
1135
new (&inst->holder ) holder_type (inst->value );
1136
1136
}
1137
+ inst->owned = true ;
1137
1138
}
1138
1139
1139
1140
// / Initialize holder object, variant 2: try to construct from existing holder object, if possible
@@ -1144,6 +1145,7 @@ class class_ : public detail::generic_type {
1144
1145
new (&inst->holder ) holder_type (*holder_ptr);
1145
1146
else
1146
1147
new (&inst->holder ) holder_type (inst->value );
1148
+ inst->owned = true ;
1147
1149
}
1148
1150
1149
1151
// / Initialize holder object, variant 3: holder is not copy constructible (e.g. unique_ptr), always initialize from raw pointer
Original file line number Diff line number Diff line change @@ -290,7 +290,28 @@ void init_issues(py::module &m) {
290
290
for (auto &e : nothrows) l.append (py::cast (e));
291
291
return l;
292
292
});
293
- }
293
+
294
+ // / Issue #471: shared pointer instance not dellocated
295
+ class SharedChild : public std ::enable_shared_from_this<SharedChild> {
296
+ public:
297
+ SharedChild () { print_created (this ); }
298
+ ~SharedChild () { print_destroyed (this ); }
299
+ };
300
+
301
+ class SharedParent {
302
+ public:
303
+ SharedParent () : child(std::make_shared<SharedChild>()) { }
304
+ const SharedChild &get_child () const { return *child; }
305
+
306
+ private:
307
+ std::shared_ptr<SharedChild> child;
308
+ };
309
+
310
+ py::class_<SharedChild, std::shared_ptr<SharedChild>>(m, " SharedChild" );
311
+ py::class_<SharedParent, std::shared_ptr<SharedParent>>(m, " SharedParent" )
312
+ .def (py::init<>())
313
+ .def (" get_child" , &SharedParent::get_child, py::return_value_policy::reference);
314
+ };
294
315
295
316
296
317
// MSVC workaround: trying to use a lambda here crashes MSCV
Original file line number Diff line number Diff line change 1
1
import pytest
2
2
import gc
3
+ from pybind11_tests import ConstructorStats
3
4
4
5
5
6
def test_regressions ():
@@ -187,3 +188,16 @@ def test_dupe_assignment():
187
188
""" Issue 461: overwriting a class with a function """
188
189
from pybind11_tests .issues import dupe_exception_failures
189
190
assert dupe_exception_failures () == []
191
+
192
+
193
+ def test_enable_shared_from_this_with_reference_rvp ():
194
+ """ Issue #471: shared pointer instance not dellocated """
195
+ from pybind11_tests import SharedParent , SharedChild
196
+
197
+ parent = SharedParent ()
198
+ child = parent .get_child ()
199
+
200
+ cstats = ConstructorStats .get (SharedChild )
201
+ assert cstats .alive () == 1
202
+ del child , parent
203
+ assert cstats .alive () == 0
You can’t perform that action at this time.
0 commit comments