PageRenderTime 43ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/pybind11/tests/test_smart_ptr.cpp

https://gitlab.com/stuckyb/fastpcm
C++ | 334 lines | 254 code | 34 blank | 46 comment | 4 complexity | 771fd48fd9d608c854bddf915cfb90eb MD5 | raw file
  1. /*
  2. tests/test_smart_ptr.cpp -- binding classes with custom reference counting,
  3. implicit conversions between types
  4. Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
  5. All rights reserved. Use of this source code is governed by a
  6. BSD-style license that can be found in the LICENSE file.
  7. */
  8. #if defined(_MSC_VER) && _MSC_VER < 1910
  9. # pragma warning(disable: 4702) // unreachable code in system header
  10. #endif
  11. #include "pybind11_tests.h"
  12. #include "object.h"
  13. // Make pybind aware of the ref-counted wrapper type (s):
  14. // ref<T> is a wrapper for 'Object' which uses intrusive reference counting
  15. // It is always possible to construct a ref<T> from an Object* pointer without
  16. // possible inconsistencies, hence the 'true' argument at the end.
  17. PYBIND11_DECLARE_HOLDER_TYPE(T, ref<T>, true);
  18. // Make pybind11 aware of the non-standard getter member function
  19. namespace pybind11 { namespace detail {
  20. template <typename T>
  21. struct holder_helper<ref<T>> {
  22. static const T *get(const ref<T> &p) { return p.get_ptr(); }
  23. };
  24. }}
  25. // The following is not required anymore for std::shared_ptr, but it should compile without error:
  26. PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>);
  27. // This is just a wrapper around unique_ptr, but with extra fields to deliberately bloat up the
  28. // holder size to trigger the non-simple-layout internal instance layout for single inheritance with
  29. // large holder type:
  30. template <typename T> class huge_unique_ptr {
  31. std::unique_ptr<T> ptr;
  32. uint64_t padding[10];
  33. public:
  34. huge_unique_ptr(T *p) : ptr(p) {};
  35. T *get() { return ptr.get(); }
  36. };
  37. PYBIND11_DECLARE_HOLDER_TYPE(T, huge_unique_ptr<T>);
  38. // Simple custom holder that works like unique_ptr
  39. template <typename T>
  40. class custom_unique_ptr {
  41. std::unique_ptr<T> impl;
  42. public:
  43. custom_unique_ptr(T* p) : impl(p) { }
  44. T* get() const { return impl.get(); }
  45. T* release_ptr() { return impl.release(); }
  46. };
  47. PYBIND11_DECLARE_HOLDER_TYPE(T, custom_unique_ptr<T>);
  48. // Simple custom holder that works like shared_ptr and has operator& overload
  49. // To obtain address of an instance of this holder pybind should use std::addressof
  50. // Attempt to get address via operator& may leads to segmentation fault
  51. template <typename T>
  52. class shared_ptr_with_addressof_operator {
  53. std::shared_ptr<T> impl;
  54. public:
  55. shared_ptr_with_addressof_operator( ) = default;
  56. shared_ptr_with_addressof_operator(T* p) : impl(p) { }
  57. T* get() const { return impl.get(); }
  58. T** operator&() { throw std::logic_error("Call of overloaded operator& is not expected"); }
  59. };
  60. PYBIND11_DECLARE_HOLDER_TYPE(T, shared_ptr_with_addressof_operator<T>);
  61. // Simple custom holder that works like unique_ptr and has operator& overload
  62. // To obtain address of an instance of this holder pybind should use std::addressof
  63. // Attempt to get address via operator& may leads to segmentation fault
  64. template <typename T>
  65. class unique_ptr_with_addressof_operator {
  66. std::unique_ptr<T> impl;
  67. public:
  68. unique_ptr_with_addressof_operator() = default;
  69. unique_ptr_with_addressof_operator(T* p) : impl(p) { }
  70. T* get() const { return impl.get(); }
  71. T* release_ptr() { return impl.release(); }
  72. T** operator&() { throw std::logic_error("Call of overloaded operator& is not expected"); }
  73. };
  74. PYBIND11_DECLARE_HOLDER_TYPE(T, unique_ptr_with_addressof_operator<T>);
  75. TEST_SUBMODULE(smart_ptr, m) {
  76. // test_smart_ptr
  77. // Object implementation in `object.h`
  78. py::class_<Object, ref<Object>> obj(m, "Object");
  79. obj.def("getRefCount", &Object::getRefCount);
  80. // Custom object with builtin reference counting (see 'object.h' for the implementation)
  81. class MyObject1 : public Object {
  82. public:
  83. MyObject1(int value) : value(value) { print_created(this, toString()); }
  84. std::string toString() const { return "MyObject1[" + std::to_string(value) + "]"; }
  85. protected:
  86. virtual ~MyObject1() { print_destroyed(this); }
  87. private:
  88. int value;
  89. };
  90. py::class_<MyObject1, ref<MyObject1>>(m, "MyObject1", obj)
  91. .def(py::init<int>());
  92. py::implicitly_convertible<py::int_, MyObject1>();
  93. m.def("make_object_1", []() -> Object * { return new MyObject1(1); });
  94. m.def("make_object_2", []() -> ref<Object> { return new MyObject1(2); });
  95. m.def("make_myobject1_1", []() -> MyObject1 * { return new MyObject1(4); });
  96. m.def("make_myobject1_2", []() -> ref<MyObject1> { return new MyObject1(5); });
  97. m.def("print_object_1", [](const Object *obj) { py::print(obj->toString()); });
  98. m.def("print_object_2", [](ref<Object> obj) { py::print(obj->toString()); });
  99. m.def("print_object_3", [](const ref<Object> &obj) { py::print(obj->toString()); });
  100. m.def("print_object_4", [](const ref<Object> *obj) { py::print((*obj)->toString()); });
  101. m.def("print_myobject1_1", [](const MyObject1 *obj) { py::print(obj->toString()); });
  102. m.def("print_myobject1_2", [](ref<MyObject1> obj) { py::print(obj->toString()); });
  103. m.def("print_myobject1_3", [](const ref<MyObject1> &obj) { py::print(obj->toString()); });
  104. m.def("print_myobject1_4", [](const ref<MyObject1> *obj) { py::print((*obj)->toString()); });
  105. // Expose constructor stats for the ref type
  106. m.def("cstats_ref", &ConstructorStats::get<ref_tag>);
  107. // Object managed by a std::shared_ptr<>
  108. class MyObject2 {
  109. public:
  110. MyObject2(int value) : value(value) { print_created(this, toString()); }
  111. std::string toString() const { return "MyObject2[" + std::to_string(value) + "]"; }
  112. virtual ~MyObject2() { print_destroyed(this); }
  113. private:
  114. int value;
  115. };
  116. py::class_<MyObject2, std::shared_ptr<MyObject2>>(m, "MyObject2")
  117. .def(py::init<int>());
  118. m.def("make_myobject2_1", []() { return new MyObject2(6); });
  119. m.def("make_myobject2_2", []() { return std::make_shared<MyObject2>(7); });
  120. m.def("print_myobject2_1", [](const MyObject2 *obj) { py::print(obj->toString()); });
  121. m.def("print_myobject2_2", [](std::shared_ptr<MyObject2> obj) { py::print(obj->toString()); });
  122. m.def("print_myobject2_3", [](const std::shared_ptr<MyObject2> &obj) { py::print(obj->toString()); });
  123. m.def("print_myobject2_4", [](const std::shared_ptr<MyObject2> *obj) { py::print((*obj)->toString()); });
  124. // Object managed by a std::shared_ptr<>, additionally derives from std::enable_shared_from_this<>
  125. class MyObject3 : public std::enable_shared_from_this<MyObject3> {
  126. public:
  127. MyObject3(int value) : value(value) { print_created(this, toString()); }
  128. std::string toString() const { return "MyObject3[" + std::to_string(value) + "]"; }
  129. virtual ~MyObject3() { print_destroyed(this); }
  130. private:
  131. int value;
  132. };
  133. py::class_<MyObject3, std::shared_ptr<MyObject3>>(m, "MyObject3")
  134. .def(py::init<int>());
  135. m.def("make_myobject3_1", []() { return new MyObject3(8); });
  136. m.def("make_myobject3_2", []() { return std::make_shared<MyObject3>(9); });
  137. m.def("print_myobject3_1", [](const MyObject3 *obj) { py::print(obj->toString()); });
  138. m.def("print_myobject3_2", [](std::shared_ptr<MyObject3> obj) { py::print(obj->toString()); });
  139. m.def("print_myobject3_3", [](const std::shared_ptr<MyObject3> &obj) { py::print(obj->toString()); });
  140. m.def("print_myobject3_4", [](const std::shared_ptr<MyObject3> *obj) { py::print((*obj)->toString()); });
  141. // test_smart_ptr_refcounting
  142. m.def("test_object1_refcounting", []() {
  143. ref<MyObject1> o = new MyObject1(0);
  144. bool good = o->getRefCount() == 1;
  145. py::object o2 = py::cast(o, py::return_value_policy::reference);
  146. // always request (partial) ownership for objects with intrusive
  147. // reference counting even when using the 'reference' RVP
  148. good &= o->getRefCount() == 2;
  149. return good;
  150. });
  151. // test_unique_nodelete
  152. // Object with a private destructor
  153. class MyObject4 {
  154. public:
  155. MyObject4(int value) : value{value} { print_created(this); }
  156. int value;
  157. private:
  158. ~MyObject4() { print_destroyed(this); }
  159. };
  160. py::class_<MyObject4, std::unique_ptr<MyObject4, py::nodelete>>(m, "MyObject4")
  161. .def(py::init<int>())
  162. .def_readwrite("value", &MyObject4::value);
  163. // test_large_holder
  164. class MyObject5 { // managed by huge_unique_ptr
  165. public:
  166. MyObject5(int value) : value{value} { print_created(this); }
  167. ~MyObject5() { print_destroyed(this); }
  168. int value;
  169. };
  170. py::class_<MyObject5, huge_unique_ptr<MyObject5>>(m, "MyObject5")
  171. .def(py::init<int>())
  172. .def_readwrite("value", &MyObject5::value);
  173. // test_shared_ptr_and_references
  174. struct SharedPtrRef {
  175. struct A {
  176. A() { print_created(this); }
  177. A(const A &) { print_copy_created(this); }
  178. A(A &&) { print_move_created(this); }
  179. ~A() { print_destroyed(this); }
  180. };
  181. A value = {};
  182. std::shared_ptr<A> shared = std::make_shared<A>();
  183. };
  184. using A = SharedPtrRef::A;
  185. py::class_<A, std::shared_ptr<A>>(m, "A");
  186. py::class_<SharedPtrRef>(m, "SharedPtrRef")
  187. .def(py::init<>())
  188. .def_readonly("ref", &SharedPtrRef::value)
  189. .def_property_readonly("copy", [](const SharedPtrRef &s) { return s.value; },
  190. py::return_value_policy::copy)
  191. .def_readonly("holder_ref", &SharedPtrRef::shared)
  192. .def_property_readonly("holder_copy", [](const SharedPtrRef &s) { return s.shared; },
  193. py::return_value_policy::copy)
  194. .def("set_ref", [](SharedPtrRef &, const A &) { return true; })
  195. .def("set_holder", [](SharedPtrRef &, std::shared_ptr<A>) { return true; });
  196. // test_shared_ptr_from_this_and_references
  197. struct SharedFromThisRef {
  198. struct B : std::enable_shared_from_this<B> {
  199. B() { print_created(this); }
  200. B(const B &) : std::enable_shared_from_this<B>() { print_copy_created(this); }
  201. B(B &&) : std::enable_shared_from_this<B>() { print_move_created(this); }
  202. ~B() { print_destroyed(this); }
  203. };
  204. B value = {};
  205. std::shared_ptr<B> shared = std::make_shared<B>();
  206. };
  207. using B = SharedFromThisRef::B;
  208. py::class_<B, std::shared_ptr<B>>(m, "B");
  209. py::class_<SharedFromThisRef>(m, "SharedFromThisRef")
  210. .def(py::init<>())
  211. .def_readonly("bad_wp", &SharedFromThisRef::value)
  212. .def_property_readonly("ref", [](const SharedFromThisRef &s) -> const B & { return *s.shared; })
  213. .def_property_readonly("copy", [](const SharedFromThisRef &s) { return s.value; },
  214. py::return_value_policy::copy)
  215. .def_readonly("holder_ref", &SharedFromThisRef::shared)
  216. .def_property_readonly("holder_copy", [](const SharedFromThisRef &s) { return s.shared; },
  217. py::return_value_policy::copy)
  218. .def("set_ref", [](SharedFromThisRef &, const B &) { return true; })
  219. .def("set_holder", [](SharedFromThisRef &, std::shared_ptr<B>) { return true; });
  220. // Issue #865: shared_from_this doesn't work with virtual inheritance
  221. struct SharedFromThisVBase : std::enable_shared_from_this<SharedFromThisVBase> {
  222. virtual ~SharedFromThisVBase() = default;
  223. };
  224. struct SharedFromThisVirt : virtual SharedFromThisVBase {};
  225. static std::shared_ptr<SharedFromThisVirt> sft(new SharedFromThisVirt());
  226. py::class_<SharedFromThisVirt, std::shared_ptr<SharedFromThisVirt>>(m, "SharedFromThisVirt")
  227. .def_static("get", []() { return sft.get(); });
  228. // test_move_only_holder
  229. struct C {
  230. C() { print_created(this); }
  231. ~C() { print_destroyed(this); }
  232. };
  233. py::class_<C, custom_unique_ptr<C>>(m, "TypeWithMoveOnlyHolder")
  234. .def_static("make", []() { return custom_unique_ptr<C>(new C); });
  235. // test_holder_with_addressof_operator
  236. struct TypeForHolderWithAddressOf {
  237. TypeForHolderWithAddressOf() { print_created(this); }
  238. TypeForHolderWithAddressOf(const TypeForHolderWithAddressOf &) { print_copy_created(this); }
  239. TypeForHolderWithAddressOf(TypeForHolderWithAddressOf &&) { print_move_created(this); }
  240. ~TypeForHolderWithAddressOf() { print_destroyed(this); }
  241. std::string toString() const {
  242. return "TypeForHolderWithAddressOf[" + std::to_string(value) + "]";
  243. }
  244. int value = 42;
  245. };
  246. using HolderWithAddressOf = shared_ptr_with_addressof_operator<TypeForHolderWithAddressOf>;
  247. py::class_<TypeForHolderWithAddressOf, HolderWithAddressOf>(m, "TypeForHolderWithAddressOf")
  248. .def_static("make", []() { return HolderWithAddressOf(new TypeForHolderWithAddressOf); })
  249. .def("get", [](const HolderWithAddressOf &self) { return self.get(); })
  250. .def("print_object_1", [](const TypeForHolderWithAddressOf *obj) { py::print(obj->toString()); })
  251. .def("print_object_2", [](HolderWithAddressOf obj) { py::print(obj.get()->toString()); })
  252. .def("print_object_3", [](const HolderWithAddressOf &obj) { py::print(obj.get()->toString()); })
  253. .def("print_object_4", [](const HolderWithAddressOf *obj) { py::print((*obj).get()->toString()); });
  254. // test_move_only_holder_with_addressof_operator
  255. struct TypeForMoveOnlyHolderWithAddressOf {
  256. TypeForMoveOnlyHolderWithAddressOf(int value) : value{value} { print_created(this); }
  257. ~TypeForMoveOnlyHolderWithAddressOf() { print_destroyed(this); }
  258. std::string toString() const {
  259. return "MoveOnlyHolderWithAddressOf[" + std::to_string(value) + "]";
  260. }
  261. int value;
  262. };
  263. using MoveOnlyHolderWithAddressOf = unique_ptr_with_addressof_operator<TypeForMoveOnlyHolderWithAddressOf>;
  264. py::class_<TypeForMoveOnlyHolderWithAddressOf, MoveOnlyHolderWithAddressOf>(m, "TypeForMoveOnlyHolderWithAddressOf")
  265. .def_static("make", []() { return MoveOnlyHolderWithAddressOf(new TypeForMoveOnlyHolderWithAddressOf(0)); })
  266. .def_readwrite("value", &TypeForMoveOnlyHolderWithAddressOf::value)
  267. .def("print_object", [](const TypeForMoveOnlyHolderWithAddressOf *obj) { py::print(obj->toString()); });
  268. // test_smart_ptr_from_default
  269. struct HeldByDefaultHolder { };
  270. py::class_<HeldByDefaultHolder>(m, "HeldByDefaultHolder")
  271. .def(py::init<>())
  272. .def_static("load_shared_ptr", [](std::shared_ptr<HeldByDefaultHolder>) {});
  273. // test_shared_ptr_gc
  274. // #187: issue involving std::shared_ptr<> return value policy & garbage collection
  275. struct ElementBase { virtual void foo() { } /* Force creation of virtual table */ };
  276. py::class_<ElementBase, std::shared_ptr<ElementBase>>(m, "ElementBase");
  277. struct ElementA : ElementBase {
  278. ElementA(int v) : v(v) { }
  279. int value() { return v; }
  280. int v;
  281. };
  282. py::class_<ElementA, ElementBase, std::shared_ptr<ElementA>>(m, "ElementA")
  283. .def(py::init<int>())
  284. .def("value", &ElementA::value);
  285. struct ElementList {
  286. void add(std::shared_ptr<ElementBase> e) { l.push_back(e); }
  287. std::vector<std::shared_ptr<ElementBase>> l;
  288. };
  289. py::class_<ElementList, std::shared_ptr<ElementList>>(m, "ElementList")
  290. .def(py::init<>())
  291. .def("add", &ElementList::add)
  292. .def("get", [](ElementList &el) {
  293. py::list list;
  294. for (auto &e : el.l)
  295. list.append(py::cast(e));
  296. return list;
  297. });
  298. }