μHAL (v2.8.17)
Part of the IPbus software repository
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
test_smart_ptr.cpp
Go to the documentation of this file.
1/*
2 tests/test_smart_ptr.cpp -- binding classes with custom reference counting,
3 implicit conversions between types
4
5 Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
6
7 All rights reserved. Use of this source code is governed by a
8 BSD-style license that can be found in the LICENSE file.
9*/
10
11#if defined(_MSC_VER) && _MSC_VER < 1910 // VS 2015's MSVC
12# pragma warning(disable : 4702) // unreachable code in system header (xatomic.h(382))
13#endif
14
15#include "object.h"
16#include "pybind11_tests.h"
17
18namespace {
19
20// This is just a wrapper around unique_ptr, but with extra fields to deliberately bloat up the
21// holder size to trigger the non-simple-layout internal instance layout for single inheritance
22// with large holder type:
23template <typename T>
24class huge_unique_ptr {
25 std::unique_ptr<T> ptr;
26 uint64_t padding[10];
27
28public:
29 explicit huge_unique_ptr(T *p) : ptr(p) {}
30 T *get() { return ptr.get(); }
31};
32
33// Simple custom holder that works like unique_ptr
34template <typename T>
35class custom_unique_ptr {
36 std::unique_ptr<T> impl;
37
38public:
39 explicit custom_unique_ptr(T *p) : impl(p) {}
40 T *get() const { return impl.get(); }
41 T *release_ptr() { return impl.release(); }
42};
43
44// Simple custom holder that works like shared_ptr and has operator& overload
45// To obtain address of an instance of this holder pybind should use std::addressof
46// Attempt to get address via operator& may leads to segmentation fault
47template <typename T>
48class shared_ptr_with_addressof_operator {
49 std::shared_ptr<T> impl;
50
51public:
52 shared_ptr_with_addressof_operator() = default;
53 explicit shared_ptr_with_addressof_operator(T *p) : impl(p) {}
54 T *get() const { return impl.get(); }
55 T **operator&() { throw std::logic_error("Call of overloaded operator& is not expected"); }
56};
57
58// Simple custom holder that works like unique_ptr and has operator& overload
59// To obtain address of an instance of this holder pybind should use std::addressof
60// Attempt to get address via operator& may leads to segmentation fault
61template <typename T>
62class unique_ptr_with_addressof_operator {
63 std::unique_ptr<T> impl;
64
65public:
66 unique_ptr_with_addressof_operator() = default;
67 explicit unique_ptr_with_addressof_operator(T *p) : impl(p) {}
68 T *get() const { return impl.get(); }
69 T *release_ptr() { return impl.release(); }
70 T **operator&() { throw std::logic_error("Call of overloaded operator& is not expected"); }
71};
72
73// Custom object with builtin reference counting (see 'object.h' for the implementation)
74class MyObject1 : public Object {
75public:
76 explicit MyObject1(int value) : value(value) { print_created(this, toString()); }
77 std::string toString() const override { return "MyObject1[" + std::to_string(value) + "]"; }
78
79protected:
80 ~MyObject1() override { print_destroyed(this); }
81
82private:
83 int value;
84};
85
86// Object managed by a std::shared_ptr<>
87class MyObject2 {
88public:
89 MyObject2(const MyObject2 &) = default;
90 explicit MyObject2(int value) : value(value) { print_created(this, toString()); }
91 std::string toString() const { return "MyObject2[" + std::to_string(value) + "]"; }
92 virtual ~MyObject2() { print_destroyed(this); }
93
94private:
95 int value;
96};
97
98// Object managed by a std::shared_ptr<>, additionally derives from std::enable_shared_from_this<>
99class MyObject3 : public std::enable_shared_from_this<MyObject3> {
100public:
101 MyObject3(const MyObject3 &) = default;
102 explicit MyObject3(int value) : value(value) { print_created(this, toString()); }
103 std::string toString() const { return "MyObject3[" + std::to_string(value) + "]"; }
104 virtual ~MyObject3() { print_destroyed(this); }
105
106private:
107 int value;
108};
109
110// test_unique_nodelete
111// Object with a private destructor
112class MyObject4;
113std::unordered_set<MyObject4 *> myobject4_instances;
114class MyObject4 {
115public:
116 explicit MyObject4(int value) : value{value} {
117 print_created(this);
118 myobject4_instances.insert(this);
119 }
120 int value;
121
122 static void cleanupAllInstances() {
123 auto tmp = std::move(myobject4_instances);
124 myobject4_instances.clear();
125 for (auto *o : tmp) {
126 delete o;
127 }
128 }
129
130private:
131 ~MyObject4() {
132 myobject4_instances.erase(this);
133 print_destroyed(this);
134 }
135};
136
137// test_unique_deleter
138// Object with std::unique_ptr<T, D> where D is not matching the base class
139// Object with a protected destructor
140class MyObject4a;
141std::unordered_set<MyObject4a *> myobject4a_instances;
142class MyObject4a {
143public:
144 explicit MyObject4a(int i) : value{i} {
145 print_created(this);
146 myobject4a_instances.insert(this);
147 };
148 int value;
149
150 static void cleanupAllInstances() {
151 auto tmp = std::move(myobject4a_instances);
152 myobject4a_instances.clear();
153 for (auto *o : tmp) {
154 delete o;
155 }
156 }
157
158protected:
159 virtual ~MyObject4a() {
160 myobject4a_instances.erase(this);
161 print_destroyed(this);
162 }
163};
164
165// Object derived but with public destructor and no Deleter in default holder
166class MyObject4b : public MyObject4a {
167public:
168 explicit MyObject4b(int i) : MyObject4a(i) { print_created(this); }
169 ~MyObject4b() override { print_destroyed(this); }
170};
171
172// test_large_holder
173class MyObject5 { // managed by huge_unique_ptr
174public:
175 explicit MyObject5(int value) : value{value} { print_created(this); }
176 ~MyObject5() { print_destroyed(this); }
177 int value;
178};
179
180// test_shared_ptr_and_references
181struct SharedPtrRef {
182 struct A {
183 A() { print_created(this); }
184 A(const A &) { print_copy_created(this); }
185 A(A &&) noexcept { print_move_created(this); }
186 ~A() { print_destroyed(this); }
187 };
188
189 A value = {};
190 std::shared_ptr<A> shared = std::make_shared<A>();
191};
192
193// test_shared_ptr_from_this_and_references
194struct SharedFromThisRef {
195 struct B : std::enable_shared_from_this<B> {
196 B() { print_created(this); }
197 // NOLINTNEXTLINE(bugprone-copy-constructor-init)
198 B(const B &) : std::enable_shared_from_this<B>() { print_copy_created(this); }
199 B(B &&) noexcept : std::enable_shared_from_this<B>() { print_move_created(this); }
200 ~B() { print_destroyed(this); }
201 };
202
203 B value = {};
204 std::shared_ptr<B> shared = std::make_shared<B>();
205};
206
207// Issue #865: shared_from_this doesn't work with virtual inheritance
208struct SharedFromThisVBase : std::enable_shared_from_this<SharedFromThisVBase> {
209 SharedFromThisVBase() = default;
210 SharedFromThisVBase(const SharedFromThisVBase &) = default;
211 virtual ~SharedFromThisVBase() = default;
212};
213struct SharedFromThisVirt : virtual SharedFromThisVBase {};
214
215// test_move_only_holder
216struct C {
217 C() { print_created(this); }
218 ~C() { print_destroyed(this); }
219};
220
221// test_holder_with_addressof_operator
222struct TypeForHolderWithAddressOf {
223 TypeForHolderWithAddressOf() { print_created(this); }
224 TypeForHolderWithAddressOf(const TypeForHolderWithAddressOf &) { print_copy_created(this); }
225 TypeForHolderWithAddressOf(TypeForHolderWithAddressOf &&) noexcept {
226 print_move_created(this);
227 }
228 ~TypeForHolderWithAddressOf() { print_destroyed(this); }
229 std::string toString() const {
230 return "TypeForHolderWithAddressOf[" + std::to_string(value) + "]";
231 }
232 int value = 42;
233};
234
235// test_move_only_holder_with_addressof_operator
236struct TypeForMoveOnlyHolderWithAddressOf {
237 explicit TypeForMoveOnlyHolderWithAddressOf(int value) : value{value} { print_created(this); }
238 ~TypeForMoveOnlyHolderWithAddressOf() { print_destroyed(this); }
239 std::string toString() const {
240 return "MoveOnlyHolderWithAddressOf[" + std::to_string(value) + "]";
241 }
242 int value;
243};
244
245// test_smart_ptr_from_default
246struct HeldByDefaultHolder {};
247
248// test_shared_ptr_gc
249// #187: issue involving std::shared_ptr<> return value policy & garbage collection
250struct ElementBase {
251 virtual ~ElementBase() = default; /* Force creation of virtual table */
252 ElementBase() = default;
253 ElementBase(const ElementBase &) = delete;
254};
255
256struct ElementA : ElementBase {
257 explicit ElementA(int v) : v(v) {}
258 int value() const { return v; }
259 int v;
260};
261
262struct ElementList {
263 void add(const std::shared_ptr<ElementBase> &e) { l.push_back(e); }
264 std::vector<std::shared_ptr<ElementBase>> l;
265};
266
267} // namespace
268
269// ref<T> is a wrapper for 'Object' which uses intrusive reference counting
270// It is always possible to construct a ref<T> from an Object* pointer without
271// possible inconsistencies, hence the 'true' argument at the end.
272// Make pybind11 aware of the non-standard getter member function
273namespace pybind11 {
274namespace detail {
275template <typename T>
276struct holder_helper<ref<T>> {
277 static const T *get(const ref<T> &p) { return p.get_ptr(); }
278};
279} // namespace detail
280} // namespace pybind11
281
282// Make pybind aware of the ref-counted wrapper type (s):
284// The following is not required anymore for std::shared_ptr, but it should compile without error:
285PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>);
286PYBIND11_DECLARE_HOLDER_TYPE(T, huge_unique_ptr<T>);
287PYBIND11_DECLARE_HOLDER_TYPE(T, custom_unique_ptr<T>);
288PYBIND11_DECLARE_HOLDER_TYPE(T, shared_ptr_with_addressof_operator<T>);
289PYBIND11_DECLARE_HOLDER_TYPE(T, unique_ptr_with_addressof_operator<T>);
290
291TEST_SUBMODULE(smart_ptr, m) {
292 // Please do not interleave `struct` and `class` definitions with bindings code,
293 // but implement `struct`s and `class`es in the anonymous namespace above.
294 // This helps keeping the smart_holder branch in sync with master.
295
296 // test_smart_ptr
297
298 // Object implementation in `object.h`
299 py::class_<Object, ref<Object>> obj(m, "Object");
300 obj.def("getRefCount", &Object::getRefCount);
301
302 py::class_<MyObject1, ref<MyObject1>>(m, "MyObject1", obj).def(py::init<int>());
303 py::implicitly_convertible<py::int_, MyObject1>();
304
305 m.def("make_object_1", []() -> Object * { return new MyObject1(1); });
306 m.def("make_object_2", []() -> ref<Object> { return ref<Object>(new MyObject1(2)); });
307 m.def("make_myobject1_1", []() -> MyObject1 * { return new MyObject1(4); });
308 m.def("make_myobject1_2", []() -> ref<MyObject1> { return ref<MyObject1>(new MyObject1(5)); });
309 m.def("print_object_1", [](const Object *obj) { py::print(obj->toString()); });
310 m.def("print_object_2", [](ref<Object> obj) { py::print(obj->toString()); });
311 m.def("print_object_3", [](const ref<Object> &obj) { py::print(obj->toString()); });
312 m.def("print_object_4", [](const ref<Object> *obj) { py::print((*obj)->toString()); });
313 m.def("print_myobject1_1", [](const MyObject1 *obj) { py::print(obj->toString()); });
314 m.def("print_myobject1_2", [](ref<MyObject1> obj) { py::print(obj->toString()); });
315 m.def("print_myobject1_3", [](const ref<MyObject1> &obj) { py::print(obj->toString()); });
316 m.def("print_myobject1_4", [](const ref<MyObject1> *obj) { py::print((*obj)->toString()); });
317
318 // Expose constructor stats for the ref type
319 m.def("cstats_ref", &ConstructorStats::get<ref_tag>);
320
321 py::class_<MyObject2, std::shared_ptr<MyObject2>>(m, "MyObject2").def(py::init<int>());
322 m.def("make_myobject2_1", []() { return new MyObject2(6); });
323 m.def("make_myobject2_2", []() { return std::make_shared<MyObject2>(7); });
324 m.def("print_myobject2_1", [](const MyObject2 *obj) { py::print(obj->toString()); });
325 // NOLINTNEXTLINE(performance-unnecessary-value-param)
326 m.def("print_myobject2_2", [](std::shared_ptr<MyObject2> obj) { py::print(obj->toString()); });
327 m.def("print_myobject2_3",
328 [](const std::shared_ptr<MyObject2> &obj) { py::print(obj->toString()); });
329 m.def("print_myobject2_4",
330 [](const std::shared_ptr<MyObject2> *obj) { py::print((*obj)->toString()); });
331
332 py::class_<MyObject3, std::shared_ptr<MyObject3>>(m, "MyObject3").def(py::init<int>());
333 m.def("make_myobject3_1", []() { return new MyObject3(8); });
334 m.def("make_myobject3_2", []() { return std::make_shared<MyObject3>(9); });
335 m.def("print_myobject3_1", [](const MyObject3 *obj) { py::print(obj->toString()); });
336 // NOLINTNEXTLINE(performance-unnecessary-value-param)
337 m.def("print_myobject3_2", [](std::shared_ptr<MyObject3> obj) { py::print(obj->toString()); });
338 m.def("print_myobject3_3",
339 [](const std::shared_ptr<MyObject3> &obj) { py::print(obj->toString()); });
340 m.def("print_myobject3_4",
341 [](const std::shared_ptr<MyObject3> *obj) { py::print((*obj)->toString()); });
342
343 // test_smart_ptr_refcounting
344 m.def("test_object1_refcounting", []() {
345 auto o = ref<MyObject1>(new MyObject1(0));
346 bool good = o->getRefCount() == 1;
347 py::object o2 = py::cast(o, py::return_value_policy::reference);
348 // always request (partial) ownership for objects with intrusive
349 // reference counting even when using the 'reference' RVP
350 good &= o->getRefCount() == 2;
351 return good;
352 });
353
354 // test_unique_nodelete
355 py::class_<MyObject4, std::unique_ptr<MyObject4, py::nodelete>>(m, "MyObject4")
356 .def(py::init<int>())
357 .def_readwrite("value", &MyObject4::value)
358 .def_static("cleanup_all_instances", &MyObject4::cleanupAllInstances);
359
360 // test_unique_deleter
361 py::class_<MyObject4a, std::unique_ptr<MyObject4a, py::nodelete>>(m, "MyObject4a")
362 .def(py::init<int>())
363 .def_readwrite("value", &MyObject4a::value)
364 .def_static("cleanup_all_instances", &MyObject4a::cleanupAllInstances);
365
366 py::class_<MyObject4b, MyObject4a, std::unique_ptr<MyObject4b>>(m, "MyObject4b")
367 .def(py::init<int>());
368
369 // test_large_holder
370 py::class_<MyObject5, huge_unique_ptr<MyObject5>>(m, "MyObject5")
371 .def(py::init<int>())
372 .def_readwrite("value", &MyObject5::value);
373
374 // test_shared_ptr_and_references
375 using A = SharedPtrRef::A;
376 py::class_<A, std::shared_ptr<A>>(m, "A");
377 py::class_<SharedPtrRef, std::unique_ptr<SharedPtrRef>>(m, "SharedPtrRef")
378 .def(py::init<>())
379 .def_readonly("ref", &SharedPtrRef::value)
380 .def_property_readonly(
381 "copy", [](const SharedPtrRef &s) { return s.value; }, py::return_value_policy::copy)
382 .def_readonly("holder_ref", &SharedPtrRef::shared)
383 .def_property_readonly(
384 "holder_copy",
385 [](const SharedPtrRef &s) { return s.shared; },
386 py::return_value_policy::copy)
387 .def("set_ref", [](SharedPtrRef &, const A &) { return true; })
388 // NOLINTNEXTLINE(performance-unnecessary-value-param)
389 .def("set_holder", [](SharedPtrRef &, std::shared_ptr<A>) { return true; });
390
391 // test_shared_ptr_from_this_and_references
392 using B = SharedFromThisRef::B;
393 py::class_<B, std::shared_ptr<B>>(m, "B");
394 py::class_<SharedFromThisRef, std::unique_ptr<SharedFromThisRef>>(m, "SharedFromThisRef")
395 .def(py::init<>())
396 .def_readonly("bad_wp", &SharedFromThisRef::value)
397 .def_property_readonly("ref",
398 [](const SharedFromThisRef &s) -> const B & { return *s.shared; })
399 .def_property_readonly(
400 "copy",
401 [](const SharedFromThisRef &s) { return s.value; },
402 py::return_value_policy::copy)
403 .def_readonly("holder_ref", &SharedFromThisRef::shared)
404 .def_property_readonly(
405 "holder_copy",
406 [](const SharedFromThisRef &s) { return s.shared; },
407 py::return_value_policy::copy)
408 .def("set_ref", [](SharedFromThisRef &, const B &) { return true; })
409 // NOLINTNEXTLINE(performance-unnecessary-value-param)
410 .def("set_holder", [](SharedFromThisRef &, std::shared_ptr<B>) { return true; });
411
412 // Issue #865: shared_from_this doesn't work with virtual inheritance
413 static std::shared_ptr<SharedFromThisVirt> sft(new SharedFromThisVirt());
414 py::class_<SharedFromThisVirt, std::shared_ptr<SharedFromThisVirt>>(m, "SharedFromThisVirt")
415 .def_static("get", []() { return sft.get(); });
416
417 // test_move_only_holder
418 py::class_<C, custom_unique_ptr<C>>(m, "TypeWithMoveOnlyHolder")
419 .def_static("make", []() { return custom_unique_ptr<C>(new C); })
420 .def_static("make_as_object", []() { return py::cast(custom_unique_ptr<C>(new C)); });
421
422 // test_holder_with_addressof_operator
423 using HolderWithAddressOf = shared_ptr_with_addressof_operator<TypeForHolderWithAddressOf>;
424 py::class_<TypeForHolderWithAddressOf, HolderWithAddressOf>(m, "TypeForHolderWithAddressOf")
425 .def_static("make", []() { return HolderWithAddressOf(new TypeForHolderWithAddressOf); })
426 .def("get", [](const HolderWithAddressOf &self) { return self.get(); })
427 .def("print_object_1",
428 [](const TypeForHolderWithAddressOf *obj) { py::print(obj->toString()); })
429 // NOLINTNEXTLINE(performance-unnecessary-value-param)
430 .def("print_object_2", [](HolderWithAddressOf obj) { py::print(obj.get()->toString()); })
431 .def("print_object_3",
432 [](const HolderWithAddressOf &obj) { py::print(obj.get()->toString()); })
433 .def("print_object_4",
434 [](const HolderWithAddressOf *obj) { py::print((*obj).get()->toString()); });
435
436 // test_move_only_holder_with_addressof_operator
437 using MoveOnlyHolderWithAddressOf
438 = unique_ptr_with_addressof_operator<TypeForMoveOnlyHolderWithAddressOf>;
439 py::class_<TypeForMoveOnlyHolderWithAddressOf, MoveOnlyHolderWithAddressOf>(
440 m, "TypeForMoveOnlyHolderWithAddressOf")
441 .def_static("make",
442 []() {
443 return MoveOnlyHolderWithAddressOf(
444 new TypeForMoveOnlyHolderWithAddressOf(0));
445 })
446 .def_readwrite("value", &TypeForMoveOnlyHolderWithAddressOf::value)
447 .def("print_object",
448 [](const TypeForMoveOnlyHolderWithAddressOf *obj) { py::print(obj->toString()); });
449
450 // test_smart_ptr_from_default
451 py::class_<HeldByDefaultHolder, std::unique_ptr<HeldByDefaultHolder>>(m, "HeldByDefaultHolder")
452 .def(py::init<>())
453 // NOLINTNEXTLINE(performance-unnecessary-value-param)
454 .def_static("load_shared_ptr", [](std::shared_ptr<HeldByDefaultHolder>) {});
455
456 // test_shared_ptr_gc
457 // #187: issue involving std::shared_ptr<> return value policy & garbage collection
458 py::class_<ElementBase, std::shared_ptr<ElementBase>>(m, "ElementBase");
459
460 py::class_<ElementA, ElementBase, std::shared_ptr<ElementA>>(m, "ElementA")
461 .def(py::init<int>())
462 .def("value", &ElementA::value);
463
464 py::class_<ElementList, std::shared_ptr<ElementList>>(m, "ElementList")
465 .def(py::init<>())
466 .def("add", &ElementList::add)
467 .def("get", [](ElementList &el) {
468 py::list list;
469 for (auto &e : el.l) {
470 list.append(py::cast(e));
471 }
472 return list;
473 });
474}
Reference counted object base class.
Definition: object.h:9
int getRefCount() const
Return the current reference count.
Definition: object.h:18
virtual std::string toString() const =0
Definition: pytypes.h:1746
void append(T &&val)
Definition: pytypes.h:1764
Reference counting helper.
Definition: object.h:67
T * get_ptr()
Return a const pointer to the referenced object.
Definition: object.h:196
std::string toString(const URI &aURI)
Definition: URI.cpp:61
#define PYBIND11_DECLARE_HOLDER_TYPE(type, holder_type,...)
Create a specialization for custom holder types (silently ignores std::shared_ptr)
Definition: cast.h:858
static const self_t self
Definition: operators.h:72
void print_copy_created(T *inst, Values &&...values)
void print_created(T *inst, Values &&...values)
void print_destroyed(T *inst, Values &&...values)
void print_move_created(T *inst, Values &&...values)
#define TEST_SUBMODULE(name, variable)
Helper class which abstracts away certain actions.
Definition: cast.h:740
static const T * get(const ref< T > &p)