You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

341 lines
12 KiB

2 months ago
  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. #include "pybind11_tests.h"
  9. #include "object.h"
  10. /// Custom object with builtin reference counting (see 'object.h' for the implementation)
  11. class MyObject1 : public Object {
  12. public:
  13. MyObject1(int value) : value(value) {
  14. print_created(this, toString());
  15. }
  16. std::string toString() const {
  17. return "MyObject1[" + std::to_string(value) + "]";
  18. }
  19. protected:
  20. virtual ~MyObject1() {
  21. print_destroyed(this);
  22. }
  23. private:
  24. int value;
  25. };
  26. /// Object managed by a std::shared_ptr<>
  27. class MyObject2 {
  28. public:
  29. MyObject2(int value) : value(value) {
  30. print_created(this, toString());
  31. }
  32. std::string toString() const {
  33. return "MyObject2[" + std::to_string(value) + "]";
  34. }
  35. virtual ~MyObject2() {
  36. print_destroyed(this);
  37. }
  38. private:
  39. int value;
  40. };
  41. /// Object managed by a std::shared_ptr<>, additionally derives from std::enable_shared_from_this<>
  42. class MyObject3 : public std::enable_shared_from_this<MyObject3> {
  43. public:
  44. MyObject3(int value) : value(value) {
  45. print_created(this, toString());
  46. }
  47. std::string toString() const {
  48. return "MyObject3[" + std::to_string(value) + "]";
  49. }
  50. virtual ~MyObject3() {
  51. print_destroyed(this);
  52. }
  53. private:
  54. int value;
  55. };
  56. class MyObject4 {
  57. public:
  58. MyObject4(int value) : value{value} {
  59. print_created(this);
  60. }
  61. int value;
  62. private:
  63. ~MyObject4() {
  64. print_destroyed(this);
  65. }
  66. };
  67. /// This is just a wrapper around unique_ptr, but with extra fields to deliberately bloat up the
  68. /// holder size to trigger the non-simple-layout internal instance layout for single inheritance with
  69. /// large holder type.
  70. template <typename T> class huge_unique_ptr {
  71. std::unique_ptr<T> ptr;
  72. uint64_t padding[10];
  73. public:
  74. huge_unique_ptr(T *p) : ptr(p) {};
  75. T *get() { return ptr.get(); }
  76. };
  77. class MyObject5 { // managed by huge_unique_ptr
  78. public:
  79. MyObject5(int value) : value{value} {
  80. print_created(this);
  81. }
  82. int value;
  83. ~MyObject5() {
  84. print_destroyed(this);
  85. }
  86. };
  87. /// Make pybind aware of the ref-counted wrapper type (s)
  88. // ref<T> is a wrapper for 'Object' which uses intrusive reference counting
  89. // It is always possible to construct a ref<T> from an Object* pointer without
  90. // possible incosistencies, hence the 'true' argument at the end.
  91. PYBIND11_DECLARE_HOLDER_TYPE(T, ref<T>, true);
  92. PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>); // Not required any more for std::shared_ptr,
  93. // but it should compile without error
  94. PYBIND11_DECLARE_HOLDER_TYPE(T, huge_unique_ptr<T>);
  95. // Make pybind11 aware of the non-standard getter member function
  96. namespace pybind11 { namespace detail {
  97. template <typename T>
  98. struct holder_helper<ref<T>> {
  99. static const T *get(const ref<T> &p) { return p.get_ptr(); }
  100. };
  101. }}
  102. Object *make_object_1() { return new MyObject1(1); }
  103. ref<Object> make_object_2() { return new MyObject1(2); }
  104. MyObject1 *make_myobject1_1() { return new MyObject1(4); }
  105. ref<MyObject1> make_myobject1_2() { return new MyObject1(5); }
  106. MyObject2 *make_myobject2_1() { return new MyObject2(6); }
  107. std::shared_ptr<MyObject2> make_myobject2_2() { return std::make_shared<MyObject2>(7); }
  108. MyObject3 *make_myobject3_1() { return new MyObject3(8); }
  109. std::shared_ptr<MyObject3> make_myobject3_2() { return std::make_shared<MyObject3>(9); }
  110. void print_object_1(const Object *obj) { py::print(obj->toString()); }
  111. void print_object_2(ref<Object> obj) { py::print(obj->toString()); }
  112. void print_object_3(const ref<Object> &obj) { py::print(obj->toString()); }
  113. void print_object_4(const ref<Object> *obj) { py::print((*obj)->toString()); }
  114. void print_myobject1_1(const MyObject1 *obj) { py::print(obj->toString()); }
  115. void print_myobject1_2(ref<MyObject1> obj) { py::print(obj->toString()); }
  116. void print_myobject1_3(const ref<MyObject1> &obj) { py::print(obj->toString()); }
  117. void print_myobject1_4(const ref<MyObject1> *obj) { py::print((*obj)->toString()); }
  118. void print_myobject2_1(const MyObject2 *obj) { py::print(obj->toString()); }
  119. void print_myobject2_2(std::shared_ptr<MyObject2> obj) { py::print(obj->toString()); }
  120. void print_myobject2_3(const std::shared_ptr<MyObject2> &obj) { py::print(obj->toString()); }
  121. void print_myobject2_4(const std::shared_ptr<MyObject2> *obj) { py::print((*obj)->toString()); }
  122. void print_myobject3_1(const MyObject3 *obj) { py::print(obj->toString()); }
  123. void print_myobject3_2(std::shared_ptr<MyObject3> obj) { py::print(obj->toString()); }
  124. void print_myobject3_3(const std::shared_ptr<MyObject3> &obj) { py::print(obj->toString()); }
  125. void print_myobject3_4(const std::shared_ptr<MyObject3> *obj) { py::print((*obj)->toString()); }
  126. test_initializer smart_ptr([](py::module &m) {
  127. py::class_<Object, ref<Object>> obj(m, "Object");
  128. obj.def("getRefCount", &Object::getRefCount);
  129. py::class_<MyObject1, ref<MyObject1>>(m, "MyObject1", obj)
  130. .def(py::init<int>());
  131. m.def("test_object1_refcounting",
  132. []() -> bool {
  133. ref<MyObject1> o = new MyObject1(0);
  134. bool good = o->getRefCount() == 1;
  135. py::object o2 = py::cast(o, py::return_value_policy::reference);
  136. // always request (partial) ownership for objects with intrusive
  137. // reference counting even when using the 'reference' RVP
  138. good &= o->getRefCount() == 2;
  139. return good;
  140. }
  141. );
  142. m.def("make_object_1", &make_object_1);
  143. m.def("make_object_2", &make_object_2);
  144. m.def("make_myobject1_1", &make_myobject1_1);
  145. m.def("make_myobject1_2", &make_myobject1_2);
  146. m.def("print_object_1", &print_object_1);
  147. m.def("print_object_2", &print_object_2);
  148. m.def("print_object_3", &print_object_3);
  149. m.def("print_object_4", &print_object_4);
  150. m.def("print_myobject1_1", &print_myobject1_1);
  151. m.def("print_myobject1_2", &print_myobject1_2);
  152. m.def("print_myobject1_3", &print_myobject1_3);
  153. m.def("print_myobject1_4", &print_myobject1_4);
  154. py::class_<MyObject2, std::shared_ptr<MyObject2>>(m, "MyObject2")
  155. .def(py::init<int>());
  156. m.def("make_myobject2_1", &make_myobject2_1);
  157. m.def("make_myobject2_2", &make_myobject2_2);
  158. m.def("print_myobject2_1", &print_myobject2_1);
  159. m.def("print_myobject2_2", &print_myobject2_2);
  160. m.def("print_myobject2_3", &print_myobject2_3);
  161. m.def("print_myobject2_4", &print_myobject2_4);
  162. py::class_<MyObject3, std::shared_ptr<MyObject3>>(m, "MyObject3")
  163. .def(py::init<int>());
  164. m.def("make_myobject3_1", &make_myobject3_1);
  165. m.def("make_myobject3_2", &make_myobject3_2);
  166. m.def("print_myobject3_1", &print_myobject3_1);
  167. m.def("print_myobject3_2", &print_myobject3_2);
  168. m.def("print_myobject3_3", &print_myobject3_3);
  169. m.def("print_myobject3_4", &print_myobject3_4);
  170. py::class_<MyObject4, std::unique_ptr<MyObject4, py::nodelete>>(m, "MyObject4")
  171. .def(py::init<int>())
  172. .def_readwrite("value", &MyObject4::value);
  173. py::class_<MyObject5, huge_unique_ptr<MyObject5>>(m, "MyObject5")
  174. .def(py::init<int>())
  175. .def_readwrite("value", &MyObject5::value);
  176. py::implicitly_convertible<py::int_, MyObject1>();
  177. // Expose constructor stats for the ref type
  178. m.def("cstats_ref", &ConstructorStats::get<ref_tag>);
  179. });
  180. struct SharedPtrRef {
  181. struct A {
  182. A() { print_created(this); }
  183. A(const A &) { print_copy_created(this); }
  184. A(A &&) { print_move_created(this); }
  185. ~A() { print_destroyed(this); }
  186. };
  187. A value = {};
  188. std::shared_ptr<A> shared = std::make_shared<A>();
  189. };
  190. struct SharedFromThisRef {
  191. struct B : std::enable_shared_from_this<B> {
  192. B() { print_created(this); }
  193. B(const B &) : std::enable_shared_from_this<B>() { print_copy_created(this); }
  194. B(B &&) : std::enable_shared_from_this<B>() { print_move_created(this); }
  195. ~B() { print_destroyed(this); }
  196. };
  197. B value = {};
  198. std::shared_ptr<B> shared = std::make_shared<B>();
  199. };
  200. // Issue #865: shared_from_this doesn't work with virtual inheritance
  201. struct SharedFromThisVBase : std::enable_shared_from_this<SharedFromThisVBase> {
  202. virtual ~SharedFromThisVBase() = default;
  203. };
  204. struct SharedFromThisVirt : virtual SharedFromThisVBase {};
  205. template <typename T>
  206. class CustomUniquePtr {
  207. std::unique_ptr<T> impl;
  208. public:
  209. CustomUniquePtr(T* p) : impl(p) { }
  210. T* get() const { return impl.get(); }
  211. T* release_ptr() { return impl.release(); }
  212. };
  213. PYBIND11_DECLARE_HOLDER_TYPE(T, CustomUniquePtr<T>);
  214. struct ElementBase { virtual void foo() { } /* Force creation of virtual table */ };
  215. struct ElementA : ElementBase {
  216. ElementA(int v) : v(v) { }
  217. int value() { return v; }
  218. int v;
  219. };
  220. struct ElementList {
  221. void add(std::shared_ptr<ElementBase> e) { l.push_back(e); }
  222. std::vector<std::shared_ptr<ElementBase>> l;
  223. };
  224. test_initializer smart_ptr_and_references([](py::module &pm) {
  225. auto m = pm.def_submodule("smart_ptr");
  226. using A = SharedPtrRef::A;
  227. py::class_<A, std::shared_ptr<A>>(m, "A");
  228. py::class_<SharedPtrRef>(m, "SharedPtrRef")
  229. .def(py::init<>())
  230. .def_readonly("ref", &SharedPtrRef::value)
  231. .def_property_readonly("copy", [](const SharedPtrRef &s) { return s.value; },
  232. py::return_value_policy::copy)
  233. .def_readonly("holder_ref", &SharedPtrRef::shared)
  234. .def_property_readonly("holder_copy", [](const SharedPtrRef &s) { return s.shared; },
  235. py::return_value_policy::copy)
  236. .def("set_ref", [](SharedPtrRef &, const A &) { return true; })
  237. .def("set_holder", [](SharedPtrRef &, std::shared_ptr<A>) { return true; });
  238. using B = SharedFromThisRef::B;
  239. py::class_<B, std::shared_ptr<B>>(m, "B");
  240. py::class_<SharedFromThisRef>(m, "SharedFromThisRef")
  241. .def(py::init<>())
  242. .def_readonly("bad_wp", &SharedFromThisRef::value)
  243. .def_property_readonly("ref", [](const SharedFromThisRef &s) -> const B & { return *s.shared; })
  244. .def_property_readonly("copy", [](const SharedFromThisRef &s) { return s.value; },
  245. py::return_value_policy::copy)
  246. .def_readonly("holder_ref", &SharedFromThisRef::shared)
  247. .def_property_readonly("holder_copy", [](const SharedFromThisRef &s) { return s.shared; },
  248. py::return_value_policy::copy)
  249. .def("set_ref", [](SharedFromThisRef &, const B &) { return true; })
  250. .def("set_holder", [](SharedFromThisRef &, std::shared_ptr<B>) { return true; });
  251. // Issue #865: shared_from_this doesn't work with virtual inheritance
  252. static std::shared_ptr<SharedFromThisVirt> sft(new SharedFromThisVirt());
  253. py::class_<SharedFromThisVirt, std::shared_ptr<SharedFromThisVirt>>(m, "SharedFromThisVirt")
  254. .def_static("get", []() { return sft.get(); });
  255. struct C {
  256. C() { print_created(this); }
  257. ~C() { print_destroyed(this); }
  258. };
  259. py::class_<C, CustomUniquePtr<C>>(m, "TypeWithMoveOnlyHolder")
  260. .def_static("make", []() { return CustomUniquePtr<C>(new C); });
  261. struct HeldByDefaultHolder { };
  262. py::class_<HeldByDefaultHolder>(m, "HeldByDefaultHolder")
  263. .def(py::init<>())
  264. .def_static("load_shared_ptr", [](std::shared_ptr<HeldByDefaultHolder>) {});
  265. // #187: issue involving std::shared_ptr<> return value policy & garbage collection
  266. py::class_<ElementBase, std::shared_ptr<ElementBase>>(m, "ElementBase");
  267. py::class_<ElementA, ElementBase, std::shared_ptr<ElementA>>(m, "ElementA")
  268. .def(py::init<int>())
  269. .def("value", &ElementA::value);
  270. py::class_<ElementList, std::shared_ptr<ElementList>>(m, "ElementList")
  271. .def(py::init<>())
  272. .def("add", &ElementList::add)
  273. .def("get", [](ElementList &el) {
  274. py::list list;
  275. for (auto &e : el.l)
  276. list.append(py::cast(e));
  277. return list;
  278. });
  279. });