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


gtsam
Author(s):
autogenerated on Sat May 8 2021 02:46:03