test_factory_constructors.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. /*
  2. tests/test_factory_constructors.cpp -- tests construction from a factory function
  3. via py::init_factory()
  4. Copyright (c) 2017 Jason Rhinelander <[email protected]>
  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 "constructor_stats.h"
  10. #include <cmath>
  11. // Classes for testing python construction via C++ factory function:
  12. // Not publicly constructible, copyable, or movable:
  13. class TestFactory1 {
  14. friend class TestFactoryHelper;
  15. TestFactory1() : value("(empty)") { print_default_created(this); }
  16. TestFactory1(int v) : value(std::to_string(v)) { print_created(this, value); }
  17. TestFactory1(std::string v) : value(std::move(v)) { print_created(this, value); }
  18. TestFactory1(TestFactory1 &&) = delete;
  19. TestFactory1(const TestFactory1 &) = delete;
  20. TestFactory1 &operator=(TestFactory1 &&) = delete;
  21. TestFactory1 &operator=(const TestFactory1 &) = delete;
  22. public:
  23. std::string value;
  24. ~TestFactory1() { print_destroyed(this); }
  25. };
  26. // Non-public construction, but moveable:
  27. class TestFactory2 {
  28. friend class TestFactoryHelper;
  29. TestFactory2() : value("(empty2)") { print_default_created(this); }
  30. TestFactory2(int v) : value(std::to_string(v)) { print_created(this, value); }
  31. TestFactory2(std::string v) : value(std::move(v)) { print_created(this, value); }
  32. public:
  33. TestFactory2(TestFactory2 &&m) { value = std::move(m.value); print_move_created(this); }
  34. TestFactory2 &operator=(TestFactory2 &&m) { value = std::move(m.value); print_move_assigned(this); return *this; }
  35. std::string value;
  36. ~TestFactory2() { print_destroyed(this); }
  37. };
  38. // Mixed direct/factory construction:
  39. class TestFactory3 {
  40. protected:
  41. friend class TestFactoryHelper;
  42. TestFactory3() : value("(empty3)") { print_default_created(this); }
  43. TestFactory3(int v) : value(std::to_string(v)) { print_created(this, value); }
  44. public:
  45. TestFactory3(std::string v) : value(std::move(v)) { print_created(this, value); }
  46. TestFactory3(TestFactory3 &&m) { value = std::move(m.value); print_move_created(this); }
  47. TestFactory3 &operator=(TestFactory3 &&m) { value = std::move(m.value); print_move_assigned(this); return *this; }
  48. std::string value;
  49. virtual ~TestFactory3() { print_destroyed(this); }
  50. };
  51. // Inheritance test
  52. class TestFactory4 : public TestFactory3 {
  53. public:
  54. TestFactory4() : TestFactory3() { print_default_created(this); }
  55. TestFactory4(int v) : TestFactory3(v) { print_created(this, v); }
  56. virtual ~TestFactory4() { print_destroyed(this); }
  57. };
  58. // Another class for an invalid downcast test
  59. class TestFactory5 : public TestFactory3 {
  60. public:
  61. TestFactory5(int i) : TestFactory3(i) { print_created(this, i); }
  62. virtual ~TestFactory5() { print_destroyed(this); }
  63. };
  64. class TestFactory6 {
  65. protected:
  66. int value;
  67. bool alias = false;
  68. public:
  69. TestFactory6(int i) : value{i} { print_created(this, i); }
  70. TestFactory6(TestFactory6 &&f) { print_move_created(this); value = f.value; alias = f.alias; }
  71. TestFactory6(const TestFactory6 &f) { print_copy_created(this); value = f.value; alias = f.alias; }
  72. virtual ~TestFactory6() { print_destroyed(this); }
  73. virtual int get() { return value; }
  74. bool has_alias() { return alias; }
  75. };
  76. class PyTF6 : public TestFactory6 {
  77. public:
  78. // Special constructor that allows the factory to construct a PyTF6 from a TestFactory6 only
  79. // when an alias is needed:
  80. PyTF6(TestFactory6 &&base) : TestFactory6(std::move(base)) { alias = true; print_created(this, "move", value); }
  81. PyTF6(int i) : TestFactory6(i) { alias = true; print_created(this, i); }
  82. PyTF6(PyTF6 &&f) : TestFactory6(std::move(f)) { print_move_created(this); }
  83. PyTF6(const PyTF6 &f) : TestFactory6(f) { print_copy_created(this); }
  84. PyTF6(std::string s) : TestFactory6((int) s.size()) { alias = true; print_created(this, s); }
  85. virtual ~PyTF6() { print_destroyed(this); }
  86. int get() override { PYBIND11_OVERLOAD(int, TestFactory6, get, /*no args*/); }
  87. };
  88. class TestFactory7 {
  89. protected:
  90. int value;
  91. bool alias = false;
  92. public:
  93. TestFactory7(int i) : value{i} { print_created(this, i); }
  94. TestFactory7(TestFactory7 &&f) { print_move_created(this); value = f.value; alias = f.alias; }
  95. TestFactory7(const TestFactory7 &f) { print_copy_created(this); value = f.value; alias = f.alias; }
  96. virtual ~TestFactory7() { print_destroyed(this); }
  97. virtual int get() { return value; }
  98. bool has_alias() { return alias; }
  99. };
  100. class PyTF7 : public TestFactory7 {
  101. public:
  102. PyTF7(int i) : TestFactory7(i) { alias = true; print_created(this, i); }
  103. PyTF7(PyTF7 &&f) : TestFactory7(std::move(f)) { print_move_created(this); }
  104. PyTF7(const PyTF7 &f) : TestFactory7(f) { print_copy_created(this); }
  105. virtual ~PyTF7() { print_destroyed(this); }
  106. int get() override { PYBIND11_OVERLOAD(int, TestFactory7, get, /*no args*/); }
  107. };
  108. class TestFactoryHelper {
  109. public:
  110. // Non-movable, non-copyable type:
  111. // Return via pointer:
  112. static TestFactory1 *construct1() { return new TestFactory1(); }
  113. // Holder:
  114. static std::unique_ptr<TestFactory1> construct1(int a) { return std::unique_ptr<TestFactory1>(new TestFactory1(a)); }
  115. // pointer again
  116. static TestFactory1 *construct1_string(std::string a) { return new TestFactory1(a); }
  117. // Moveable type:
  118. // pointer:
  119. static TestFactory2 *construct2() { return new TestFactory2(); }
  120. // holder:
  121. static std::unique_ptr<TestFactory2> construct2(int a) { return std::unique_ptr<TestFactory2>(new TestFactory2(a)); }
  122. // by value moving:
  123. static TestFactory2 construct2(std::string a) { return TestFactory2(a); }
  124. // shared_ptr holder type:
  125. // pointer:
  126. static TestFactory3 *construct3() { return new TestFactory3(); }
  127. // holder:
  128. static std::shared_ptr<TestFactory3> construct3(int a) { return std::shared_ptr<TestFactory3>(new TestFactory3(a)); }
  129. };
  130. TEST_SUBMODULE(factory_constructors, m) {
  131. // Define various trivial types to allow simpler overload resolution:
  132. py::module m_tag = m.def_submodule("tag");
  133. #define MAKE_TAG_TYPE(Name) \
  134. struct Name##_tag {}; \
  135. py::class_<Name##_tag>(m_tag, #Name "_tag").def(py::init<>()); \
  136. m_tag.attr(#Name) = py::cast(Name##_tag{})
  137. MAKE_TAG_TYPE(pointer);
  138. MAKE_TAG_TYPE(unique_ptr);
  139. MAKE_TAG_TYPE(move);
  140. MAKE_TAG_TYPE(shared_ptr);
  141. MAKE_TAG_TYPE(derived);
  142. MAKE_TAG_TYPE(TF4);
  143. MAKE_TAG_TYPE(TF5);
  144. MAKE_TAG_TYPE(null_ptr);
  145. MAKE_TAG_TYPE(base);
  146. MAKE_TAG_TYPE(invalid_base);
  147. MAKE_TAG_TYPE(alias);
  148. MAKE_TAG_TYPE(unaliasable);
  149. MAKE_TAG_TYPE(mixed);
  150. // test_init_factory_basic, test_bad_type
  151. py::class_<TestFactory1>(m, "TestFactory1")
  152. .def(py::init([](unique_ptr_tag, int v) { return TestFactoryHelper::construct1(v); }))
  153. .def(py::init(&TestFactoryHelper::construct1_string)) // raw function pointer
  154. .def(py::init([](pointer_tag) { return TestFactoryHelper::construct1(); }))
  155. .def(py::init([](py::handle, int v, py::handle) { return TestFactoryHelper::construct1(v); }))
  156. .def_readwrite("value", &TestFactory1::value)
  157. ;
  158. py::class_<TestFactory2>(m, "TestFactory2")
  159. .def(py::init([](pointer_tag, int v) { return TestFactoryHelper::construct2(v); }))
  160. .def(py::init([](unique_ptr_tag, std::string v) { return TestFactoryHelper::construct2(v); }))
  161. .def(py::init([](move_tag) { return TestFactoryHelper::construct2(); }))
  162. .def_readwrite("value", &TestFactory2::value)
  163. ;
  164. // Stateful & reused:
  165. int c = 1;
  166. auto c4a = [c](pointer_tag, TF4_tag, int a) { (void) c; return new TestFactory4(a);};
  167. // test_init_factory_basic, test_init_factory_casting
  168. py::class_<TestFactory3, std::shared_ptr<TestFactory3>>(m, "TestFactory3")
  169. .def(py::init([](pointer_tag, int v) { return TestFactoryHelper::construct3(v); }))
  170. .def(py::init([](shared_ptr_tag) { return TestFactoryHelper::construct3(); }))
  171. .def("__init__", [](TestFactory3 &self, std::string v) { new (&self) TestFactory3(v); }) // placement-new ctor
  172. // factories returning a derived type:
  173. .def(py::init(c4a)) // derived ptr
  174. .def(py::init([](pointer_tag, TF5_tag, int a) { return new TestFactory5(a); }))
  175. // derived shared ptr:
  176. .def(py::init([](shared_ptr_tag, TF4_tag, int a) { return std::make_shared<TestFactory4>(a); }))
  177. .def(py::init([](shared_ptr_tag, TF5_tag, int a) { return std::make_shared<TestFactory5>(a); }))
  178. // Returns nullptr:
  179. .def(py::init([](null_ptr_tag) { return (TestFactory3 *) nullptr; }))
  180. .def_readwrite("value", &TestFactory3::value)
  181. ;
  182. // test_init_factory_casting
  183. py::class_<TestFactory4, TestFactory3, std::shared_ptr<TestFactory4>>(m, "TestFactory4")
  184. .def(py::init(c4a)) // pointer
  185. ;
  186. // Doesn't need to be registered, but registering makes getting ConstructorStats easier:
  187. py::class_<TestFactory5, TestFactory3, std::shared_ptr<TestFactory5>>(m, "TestFactory5");
  188. // test_init_factory_alias
  189. // Alias testing
  190. py::class_<TestFactory6, PyTF6>(m, "TestFactory6")
  191. .def(py::init([](base_tag, int i) { return TestFactory6(i); }))
  192. .def(py::init([](alias_tag, int i) { return PyTF6(i); }))
  193. .def(py::init([](alias_tag, std::string s) { return PyTF6(s); }))
  194. .def(py::init([](alias_tag, pointer_tag, int i) { return new PyTF6(i); }))
  195. .def(py::init([](base_tag, pointer_tag, int i) { return new TestFactory6(i); }))
  196. .def(py::init([](base_tag, alias_tag, pointer_tag, int i) { return (TestFactory6 *) new PyTF6(i); }))
  197. .def("get", &TestFactory6::get)
  198. .def("has_alias", &TestFactory6::has_alias)
  199. .def_static("get_cstats", &ConstructorStats::get<TestFactory6>, py::return_value_policy::reference)
  200. .def_static("get_alias_cstats", &ConstructorStats::get<PyTF6>, py::return_value_policy::reference)
  201. ;
  202. // test_init_factory_dual
  203. // Separate alias constructor testing
  204. py::class_<TestFactory7, PyTF7, std::shared_ptr<TestFactory7>>(m, "TestFactory7")
  205. .def(py::init(
  206. [](int i) { return TestFactory7(i); },
  207. [](int i) { return PyTF7(i); }))
  208. .def(py::init(
  209. [](pointer_tag, int i) { return new TestFactory7(i); },
  210. [](pointer_tag, int i) { return new PyTF7(i); }))
  211. .def(py::init(
  212. [](mixed_tag, int i) { return new TestFactory7(i); },
  213. [](mixed_tag, int i) { return PyTF7(i); }))
  214. .def(py::init(
  215. [](mixed_tag, std::string s) { return TestFactory7((int) s.size()); },
  216. [](mixed_tag, std::string s) { return new PyTF7((int) s.size()); }))
  217. .def(py::init(
  218. [](base_tag, pointer_tag, int i) { return new TestFactory7(i); },
  219. [](base_tag, pointer_tag, int i) { return (TestFactory7 *) new PyTF7(i); }))
  220. .def(py::init(
  221. [](alias_tag, pointer_tag, int i) { return new PyTF7(i); },
  222. [](alias_tag, pointer_tag, int i) { return new PyTF7(10*i); }))
  223. .def(py::init(
  224. [](shared_ptr_tag, base_tag, int i) { return std::make_shared<TestFactory7>(i); },
  225. [](shared_ptr_tag, base_tag, int i) { auto *p = new PyTF7(i); return std::shared_ptr<TestFactory7>(p); }))
  226. .def(py::init(
  227. [](shared_ptr_tag, invalid_base_tag, int i) { return std::make_shared<TestFactory7>(i); },
  228. [](shared_ptr_tag, invalid_base_tag, int i) { return std::make_shared<TestFactory7>(i); })) // <-- invalid alias factory
  229. .def("get", &TestFactory7::get)
  230. .def("has_alias", &TestFactory7::has_alias)
  231. .def_static("get_cstats", &ConstructorStats::get<TestFactory7>, py::return_value_policy::reference)
  232. .def_static("get_alias_cstats", &ConstructorStats::get<PyTF7>, py::return_value_policy::reference)
  233. ;
  234. // test_placement_new_alternative
  235. // Class with a custom new operator but *without* a placement new operator (issue #948)
  236. class NoPlacementNew {
  237. public:
  238. NoPlacementNew(int i) : i(i) { }
  239. static void *operator new(std::size_t s) {
  240. auto *p = ::operator new(s);
  241. py::print("operator new called, returning", reinterpret_cast<uintptr_t>(p));
  242. return p;
  243. }
  244. static void operator delete(void *p) {
  245. py::print("operator delete called on", reinterpret_cast<uintptr_t>(p));
  246. ::operator delete(p);
  247. }
  248. int i;
  249. };
  250. // As of 2.2, `py::init<args>` no longer requires placement new
  251. py::class_<NoPlacementNew>(m, "NoPlacementNew")
  252. .def(py::init<int>())
  253. .def(py::init([]() { return new NoPlacementNew(100); }))
  254. .def_readwrite("i", &NoPlacementNew::i)
  255. ;
  256. // test_reallocations
  257. // Class that has verbose operator_new/operator_delete calls
  258. struct NoisyAlloc {
  259. NoisyAlloc(int i) { py::print(py::str("NoisyAlloc(int {})").format(i)); }
  260. NoisyAlloc(double d) { py::print(py::str("NoisyAlloc(double {})").format(d)); }
  261. ~NoisyAlloc() { py::print("~NoisyAlloc()"); }
  262. static void *operator new(size_t s) { py::print("noisy new"); return ::operator new(s); }
  263. static void *operator new(size_t, void *p) { py::print("noisy placement new"); return p; }
  264. static void operator delete(void *p, size_t) { py::print("noisy delete"); ::operator delete(p); }
  265. static void operator delete(void *, void *) { py::print("noisy placement delete"); }
  266. #if defined(_MSC_VER) && _MSC_VER < 1910
  267. // MSVC 2015 bug: the above "noisy delete" isn't invoked (fixed in MSVC 2017)
  268. static void operator delete(void *p) { py::print("noisy delete"); ::operator delete(p); }
  269. #endif
  270. };
  271. py::class_<NoisyAlloc>(m, "NoisyAlloc")
  272. // Since these overloads have the same number of arguments, the dispatcher will try each of
  273. // them until the arguments convert. Thus we can get a pre-allocation here when passing a
  274. // single non-integer:
  275. .def("__init__", [](NoisyAlloc *a, int i) { new (a) NoisyAlloc(i); }) // Regular constructor, runs first, requires preallocation
  276. .def(py::init([](double d) { return new NoisyAlloc(d); }))
  277. // The two-argument version: first the factory pointer overload.
  278. .def(py::init([](int i, int) { return new NoisyAlloc(i); }))
  279. // Return-by-value:
  280. .def(py::init([](double d, int) { return NoisyAlloc(d); }))
  281. // Old-style placement new init; requires preallocation
  282. .def("__init__", [](NoisyAlloc &a, double d, double) { new (&a) NoisyAlloc(d); })
  283. // Requires deallocation of previous overload preallocated value:
  284. .def(py::init([](int i, double) { return new NoisyAlloc(i); }))
  285. // Regular again: requires yet another preallocation
  286. .def("__init__", [](NoisyAlloc &a, int i, std::string) { new (&a) NoisyAlloc(i); })
  287. ;
  288. // static_assert testing (the following def's should all fail with appropriate compilation errors):
  289. #if 0
  290. struct BadF1Base {};
  291. struct BadF1 : BadF1Base {};
  292. struct PyBadF1 : BadF1 {};
  293. py::class_<BadF1, PyBadF1, std::shared_ptr<BadF1>> bf1(m, "BadF1");
  294. // wrapped factory function must return a compatible pointer, holder, or value
  295. bf1.def(py::init([]() { return 3; }));
  296. // incompatible factory function pointer return type
  297. bf1.def(py::init([]() { static int three = 3; return &three; }));
  298. // incompatible factory function std::shared_ptr<T> return type: cannot convert shared_ptr<T> to holder
  299. // (non-polymorphic base)
  300. bf1.def(py::init([]() { return std::shared_ptr<BadF1Base>(new BadF1()); }));
  301. #endif
  302. }