1 /*
2 tests/test_class.cpp -- test py::class_ definitions and basic functionality
3
4 Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
5
6 All rights reserved. Use of this source code is governed by a
7 BSD-style license that can be found in the LICENSE file.
8 */
9
10 #if defined(__INTEL_COMPILER) && __cplusplus >= 201703L
11 // Intel compiler requires a separate header file to support aligned new operators
12 // and does not set the __cpp_aligned_new feature macro.
13 // This header needs to be included before pybind11.
14 #include <aligned_new>
15 #endif
16
17 #include "pybind11_tests.h"
18 #include "constructor_stats.h"
19 #include "local_bindings.h"
20 #include <pybind11/stl.h>
21
22 #if defined(_MSC_VER)
23 # pragma warning(disable: 4324) // warning C4324: structure was padded due to alignment specifier
24 #endif
25
26 // test_brace_initialization
27 struct NoBraceInitialization {
NoBraceInitializationNoBraceInitialization28 NoBraceInitialization(std::vector<int> v) : vec{std::move(v)} {}
29 template <typename T>
NoBraceInitializationNoBraceInitialization30 NoBraceInitialization(std::initializer_list<T> l) : vec(l) {}
31
32 std::vector<int> vec;
33 };
34
TEST_SUBMODULE(class_,m)35 TEST_SUBMODULE(class_, m) {
36 // test_instance
37 struct NoConstructor {
38 NoConstructor() = default;
39 NoConstructor(const NoConstructor &) = default;
40 NoConstructor(NoConstructor &&) = default;
41 static NoConstructor *new_instance() {
42 auto *ptr = new NoConstructor();
43 print_created(ptr, "via new_instance");
44 return ptr;
45 }
46 ~NoConstructor() { print_destroyed(this); }
47 };
48
49 py::class_<NoConstructor>(m, "NoConstructor")
50 .def_static("new_instance", &NoConstructor::new_instance, "Return an instance");
51
52 // test_inheritance
53 class Pet {
54 public:
55 Pet(const std::string &name, const std::string &species)
56 : m_name(name), m_species(species) {}
57 std::string name() const { return m_name; }
58 std::string species() const { return m_species; }
59 private:
60 std::string m_name;
61 std::string m_species;
62 };
63
64 class Dog : public Pet {
65 public:
66 Dog(const std::string &name) : Pet(name, "dog") {}
67 std::string bark() const { return "Woof!"; }
68 };
69
70 class Rabbit : public Pet {
71 public:
72 Rabbit(const std::string &name) : Pet(name, "parrot") {}
73 };
74
75 class Hamster : public Pet {
76 public:
77 Hamster(const std::string &name) : Pet(name, "rodent") {}
78 };
79
80 class Chimera : public Pet {
81 Chimera() : Pet("Kimmy", "chimera") {}
82 };
83
84 py::class_<Pet> pet_class(m, "Pet");
85 pet_class
86 .def(py::init<std::string, std::string>())
87 .def("name", &Pet::name)
88 .def("species", &Pet::species);
89
90 /* One way of declaring a subclass relationship: reference parent's class_ object */
91 py::class_<Dog>(m, "Dog", pet_class)
92 .def(py::init<std::string>());
93
94 /* Another way of declaring a subclass relationship: reference parent's C++ type */
95 py::class_<Rabbit, Pet>(m, "Rabbit")
96 .def(py::init<std::string>());
97
98 /* And another: list parent in class template arguments */
99 py::class_<Hamster, Pet>(m, "Hamster")
100 .def(py::init<std::string>());
101
102 /* Constructors are not inherited by default */
103 py::class_<Chimera, Pet>(m, "Chimera");
104
105 m.def("pet_name_species", [](const Pet &pet) { return pet.name() + " is a " + pet.species(); });
106 m.def("dog_bark", [](const Dog &dog) { return dog.bark(); });
107
108 // test_automatic_upcasting
109 struct BaseClass {
110 BaseClass() = default;
111 BaseClass(const BaseClass &) = default;
112 BaseClass(BaseClass &&) = default;
113 virtual ~BaseClass() = default;
114 };
115 struct DerivedClass1 : BaseClass { };
116 struct DerivedClass2 : BaseClass { };
117
118 py::class_<BaseClass>(m, "BaseClass").def(py::init<>());
119 py::class_<DerivedClass1>(m, "DerivedClass1").def(py::init<>());
120 py::class_<DerivedClass2>(m, "DerivedClass2").def(py::init<>());
121
122 m.def("return_class_1", []() -> BaseClass* { return new DerivedClass1(); });
123 m.def("return_class_2", []() -> BaseClass* { return new DerivedClass2(); });
124 m.def("return_class_n", [](int n) -> BaseClass* {
125 if (n == 1) return new DerivedClass1();
126 if (n == 2) return new DerivedClass2();
127 return new BaseClass();
128 });
129 m.def("return_none", []() -> BaseClass* { return nullptr; });
130
131 // test_isinstance
132 m.def("check_instances", [](py::list l) {
133 return py::make_tuple(
134 py::isinstance<py::tuple>(l[0]),
135 py::isinstance<py::dict>(l[1]),
136 py::isinstance<Pet>(l[2]),
137 py::isinstance<Pet>(l[3]),
138 py::isinstance<Dog>(l[4]),
139 py::isinstance<Rabbit>(l[5]),
140 py::isinstance<UnregisteredType>(l[6])
141 );
142 });
143
144 struct Invalid {};
145
146 // test_type
147 m.def("check_type", [](int category) {
148 // Currently not supported (via a fail at compile time)
149 // See https://github.com/pybind/pybind11/issues/2486
150 // if (category == 2)
151 // return py::type::of<int>();
152 if (category == 1)
153 return py::type::of<DerivedClass1>();
154 else
155 return py::type::of<Invalid>();
156 });
157
158 m.def("get_type_of", [](py::object ob) {
159 return py::type::of(ob);
160 });
161
162 m.def("get_type_classic", [](py::handle h) {
163 return h.get_type();
164 });
165
166 m.def("as_type", [](py::object ob) {
167 return py::type(ob);
168 });
169
170 // test_mismatched_holder
171 struct MismatchBase1 { };
172 struct MismatchDerived1 : MismatchBase1 { };
173
174 struct MismatchBase2 { };
175 struct MismatchDerived2 : MismatchBase2 { };
176
177 m.def("mismatched_holder_1", []() {
178 auto mod = py::module_::import("__main__");
179 py::class_<MismatchBase1, std::shared_ptr<MismatchBase1>>(mod, "MismatchBase1");
180 py::class_<MismatchDerived1, MismatchBase1>(mod, "MismatchDerived1");
181 });
182 m.def("mismatched_holder_2", []() {
183 auto mod = py::module_::import("__main__");
184 py::class_<MismatchBase2>(mod, "MismatchBase2");
185 py::class_<MismatchDerived2, std::shared_ptr<MismatchDerived2>,
186 MismatchBase2>(mod, "MismatchDerived2");
187 });
188
189 // test_override_static
190 // #511: problem with inheritance + overwritten def_static
191 struct MyBase {
192 static std::unique_ptr<MyBase> make() {
193 return std::unique_ptr<MyBase>(new MyBase());
194 }
195 };
196
197 struct MyDerived : MyBase {
198 static std::unique_ptr<MyDerived> make() {
199 return std::unique_ptr<MyDerived>(new MyDerived());
200 }
201 };
202
203 py::class_<MyBase>(m, "MyBase")
204 .def_static("make", &MyBase::make);
205
206 py::class_<MyDerived, MyBase>(m, "MyDerived")
207 .def_static("make", &MyDerived::make)
208 .def_static("make2", &MyDerived::make);
209
210 // test_implicit_conversion_life_support
211 struct ConvertibleFromUserType {
212 int i;
213
214 ConvertibleFromUserType(UserType u) : i(u.value()) { }
215 };
216
217 py::class_<ConvertibleFromUserType>(m, "AcceptsUserType")
218 .def(py::init<UserType>());
219 py::implicitly_convertible<UserType, ConvertibleFromUserType>();
220
221 m.def("implicitly_convert_argument", [](const ConvertibleFromUserType &r) { return r.i; });
222 m.def("implicitly_convert_variable", [](py::object o) {
223 // `o` is `UserType` and `r` is a reference to a temporary created by implicit
224 // conversion. This is valid when called inside a bound function because the temp
225 // object is attached to the same life support system as the arguments.
226 const auto &r = o.cast<const ConvertibleFromUserType &>();
227 return r.i;
228 });
229 m.add_object("implicitly_convert_variable_fail", [&] {
230 auto f = [](PyObject *, PyObject *args) -> PyObject * {
231 auto o = py::reinterpret_borrow<py::tuple>(args)[0];
232 try { // It should fail here because there is no life support.
233 o.cast<const ConvertibleFromUserType &>();
234 } catch (const py::cast_error &e) {
235 return py::str(e.what()).release().ptr();
236 }
237 return py::str().release().ptr();
238 };
239
240 auto def = new PyMethodDef{"f", f, METH_VARARGS, nullptr};
241 py::capsule def_capsule(def, [](void *ptr) { delete reinterpret_cast<PyMethodDef *>(ptr); });
242 return py::reinterpret_steal<py::object>(PyCFunction_NewEx(def, def_capsule.ptr(), m.ptr()));
243 }());
244
245 // test_operator_new_delete
246 struct HasOpNewDel {
247 std::uint64_t i;
248 static void *operator new(size_t s) { py::print("A new", s); return ::operator new(s); }
249 static void *operator new(size_t s, void *ptr) { py::print("A placement-new", s); return ptr; }
250 static void operator delete(void *p) { py::print("A delete"); return ::operator delete(p); }
251 };
252 struct HasOpNewDelSize {
253 std::uint32_t i;
254 static void *operator new(size_t s) { py::print("B new", s); return ::operator new(s); }
255 static void *operator new(size_t s, void *ptr) { py::print("B placement-new", s); return ptr; }
256 static void operator delete(void *p, size_t s) { py::print("B delete", s); return ::operator delete(p); }
257 };
258 struct AliasedHasOpNewDelSize {
259 std::uint64_t i;
260 static void *operator new(size_t s) { py::print("C new", s); return ::operator new(s); }
261 static void *operator new(size_t s, void *ptr) { py::print("C placement-new", s); return ptr; }
262 static void operator delete(void *p, size_t s) { py::print("C delete", s); return ::operator delete(p); }
263 virtual ~AliasedHasOpNewDelSize() = default;
264 AliasedHasOpNewDelSize() = default;
265 AliasedHasOpNewDelSize(const AliasedHasOpNewDelSize&) = delete;
266 };
267 struct PyAliasedHasOpNewDelSize : AliasedHasOpNewDelSize {
268 PyAliasedHasOpNewDelSize() = default;
269 PyAliasedHasOpNewDelSize(int) { }
270 std::uint64_t j;
271 };
272 struct HasOpNewDelBoth {
273 std::uint32_t i[8];
274 static void *operator new(size_t s) { py::print("D new", s); return ::operator new(s); }
275 static void *operator new(size_t s, void *ptr) { py::print("D placement-new", s); return ptr; }
276 static void operator delete(void *p) { py::print("D delete"); return ::operator delete(p); }
277 static void operator delete(void *p, size_t s) { py::print("D wrong delete", s); return ::operator delete(p); }
278 };
279 py::class_<HasOpNewDel>(m, "HasOpNewDel").def(py::init<>());
280 py::class_<HasOpNewDelSize>(m, "HasOpNewDelSize").def(py::init<>());
281 py::class_<HasOpNewDelBoth>(m, "HasOpNewDelBoth").def(py::init<>());
282 py::class_<AliasedHasOpNewDelSize, PyAliasedHasOpNewDelSize> aliased(m, "AliasedHasOpNewDelSize");
283 aliased.def(py::init<>());
284 aliased.attr("size_noalias") = py::int_(sizeof(AliasedHasOpNewDelSize));
285 aliased.attr("size_alias") = py::int_(sizeof(PyAliasedHasOpNewDelSize));
286
287 // This test is actually part of test_local_bindings (test_duplicate_local), but we need a
288 // definition in a different compilation unit within the same module:
289 bind_local<LocalExternal, 17>(m, "LocalExternal", py::module_local());
290
291 // test_bind_protected_functions
292 class ProtectedA {
293 protected:
294 int foo() const { return value; }
295
296 private:
297 int value = 42;
298 };
299
300 class PublicistA : public ProtectedA {
301 public:
302 using ProtectedA::foo;
303 };
304
305 py::class_<ProtectedA>(m, "ProtectedA")
306 .def(py::init<>())
307 #if !defined(_MSC_VER) || _MSC_VER >= 1910
308 .def("foo", &PublicistA::foo);
309 #else
310 .def("foo", static_cast<int (ProtectedA::*)() const>(&PublicistA::foo));
311 #endif
312
313 class ProtectedB {
314 public:
315 virtual ~ProtectedB() = default;
316 ProtectedB() = default;
317 ProtectedB(const ProtectedB &) = delete;
318
319 protected:
320 virtual int foo() const { return value; }
321
322 private:
323 int value = 42;
324 };
325
326 class TrampolineB : public ProtectedB {
327 public:
328 int foo() const override { PYBIND11_OVERRIDE(int, ProtectedB, foo, ); }
329 };
330
331 class PublicistB : public ProtectedB {
332 public:
333 // [workaround(intel)] = default does not work here
334 // Removing or defaulting this destructor results in linking errors with the Intel compiler
335 // (in Debug builds only, tested with icpc (ICC) 2021.1 Beta 20200827)
336 ~PublicistB() override {}; // NOLINT(modernize-use-equals-default)
337 using ProtectedB::foo;
338 };
339
340 py::class_<ProtectedB, TrampolineB>(m, "ProtectedB")
341 .def(py::init<>())
342 #if !defined(_MSC_VER) || _MSC_VER >= 1910
343 .def("foo", &PublicistB::foo);
344 #else
345 .def("foo", static_cast<int (ProtectedB::*)() const>(&PublicistB::foo));
346 #endif
347
348 // test_brace_initialization
349 struct BraceInitialization {
350 int field1;
351 std::string field2;
352 };
353
354 py::class_<BraceInitialization>(m, "BraceInitialization")
355 .def(py::init<int, const std::string &>())
356 .def_readwrite("field1", &BraceInitialization::field1)
357 .def_readwrite("field2", &BraceInitialization::field2);
358 // We *don't* want to construct using braces when the given constructor argument maps to a
359 // constructor, because brace initialization could go to the wrong place (in particular when
360 // there is also an `initializer_list<T>`-accept constructor):
361 py::class_<NoBraceInitialization>(m, "NoBraceInitialization")
362 .def(py::init<std::vector<int>>())
363 .def_readonly("vec", &NoBraceInitialization::vec);
364
365 // test_reentrant_implicit_conversion_failure
366 // #1035: issue with runaway reentrant implicit conversion
367 struct BogusImplicitConversion {
368 BogusImplicitConversion(const BogusImplicitConversion &) = default;
369 };
370
371 py::class_<BogusImplicitConversion>(m, "BogusImplicitConversion")
372 .def(py::init<const BogusImplicitConversion &>());
373
374 py::implicitly_convertible<int, BogusImplicitConversion>();
375
376 // test_qualname
377 // #1166: nested class docstring doesn't show nested name
378 // Also related: tests that __qualname__ is set properly
379 struct NestBase {};
380 struct Nested {};
381 py::class_<NestBase> base(m, "NestBase");
382 base.def(py::init<>());
383 py::class_<Nested>(base, "Nested")
384 .def(py::init<>())
385 .def("fn", [](Nested &, int, NestBase &, Nested &) {})
386 .def("fa", [](Nested &, int, NestBase &, Nested &) {},
387 "a"_a, "b"_a, "c"_a);
388 base.def("g", [](NestBase &, Nested &) {});
389 base.def("h", []() { return NestBase(); });
390
391 // test_error_after_conversion
392 // The second-pass path through dispatcher() previously didn't
393 // remember which overload was used, and would crash trying to
394 // generate a useful error message
395
396 struct NotRegistered {};
397 struct StringWrapper { std::string str; };
398 m.def("test_error_after_conversions", [](int) {});
399 m.def("test_error_after_conversions",
400 [](StringWrapper) -> NotRegistered { return {}; });
401 py::class_<StringWrapper>(m, "StringWrapper").def(py::init<std::string>());
402 py::implicitly_convertible<std::string, StringWrapper>();
403
404 #if defined(PYBIND11_CPP17)
405 struct alignas(1024) Aligned {
406 std::uintptr_t ptr() const { return (uintptr_t) this; }
407 };
408 py::class_<Aligned>(m, "Aligned")
409 .def(py::init<>())
410 .def("ptr", &Aligned::ptr);
411 #endif
412
413 // test_final
414 struct IsFinal final {};
415 py::class_<IsFinal>(m, "IsFinal", py::is_final());
416
417 // test_non_final_final
418 struct IsNonFinalFinal {};
419 py::class_<IsNonFinalFinal>(m, "IsNonFinalFinal", py::is_final());
420
421 // test_exception_rvalue_abort
422 struct PyPrintDestructor {
423 PyPrintDestructor() = default;
424 ~PyPrintDestructor() {
425 py::print("Print from destructor");
426 }
427 void throw_something() { throw std::runtime_error("error"); }
428 };
429 py::class_<PyPrintDestructor>(m, "PyPrintDestructor")
430 .def(py::init<>())
431 .def("throw_something", &PyPrintDestructor::throw_something);
432
433 // test_multiple_instances_with_same_pointer
434 struct SamePointer {};
435 static SamePointer samePointer;
436 py::class_<SamePointer, std::unique_ptr<SamePointer, py::nodelete>>(m, "SamePointer")
437 .def(py::init([]() { return &samePointer; }))
438 .def("__del__", [](SamePointer&) { py::print("__del__ called"); });
439
440 struct Empty {};
441 py::class_<Empty>(m, "Empty")
442 .def(py::init<>());
443
444 // test_base_and_derived_nested_scope
445 struct BaseWithNested {
446 struct Nested {};
447 };
448
449 struct DerivedWithNested : BaseWithNested {
450 struct Nested {};
451 };
452
453 py::class_<BaseWithNested> baseWithNested_class(m, "BaseWithNested");
454 py::class_<DerivedWithNested, BaseWithNested> derivedWithNested_class(m, "DerivedWithNested");
455 py::class_<BaseWithNested::Nested>(baseWithNested_class, "Nested")
456 .def_static("get_name", []() { return "BaseWithNested::Nested"; });
457 py::class_<DerivedWithNested::Nested>(derivedWithNested_class, "Nested")
458 .def_static("get_name", []() { return "DerivedWithNested::Nested"; });
459
460 // test_register_duplicate_class
461 struct Duplicate {};
462 struct OtherDuplicate {};
463 struct DuplicateNested {};
464 struct OtherDuplicateNested {};
465 m.def("register_duplicate_class_name", [](py::module_ m) {
466 py::class_<Duplicate>(m, "Duplicate");
467 py::class_<OtherDuplicate>(m, "Duplicate");
468 });
469 m.def("register_duplicate_class_type", [](py::module_ m) {
470 py::class_<OtherDuplicate>(m, "OtherDuplicate");
471 py::class_<OtherDuplicate>(m, "YetAnotherDuplicate");
472 });
473 m.def("register_duplicate_nested_class_name", [](py::object gt) {
474 py::class_<DuplicateNested>(gt, "DuplicateNested");
475 py::class_<OtherDuplicateNested>(gt, "DuplicateNested");
476 });
477 m.def("register_duplicate_nested_class_type", [](py::object gt) {
478 py::class_<OtherDuplicateNested>(gt, "OtherDuplicateNested");
479 py::class_<OtherDuplicateNested>(gt, "YetAnotherDuplicateNested");
480 });
481 }
482
483 template <int N> class BreaksBase { public:
484 virtual ~BreaksBase() = default;
485 BreaksBase() = default;
486 BreaksBase(const BreaksBase&) = delete;
487 };
488 template <int N> class BreaksTramp : public BreaksBase<N> {};
489 // These should all compile just fine:
490 using DoesntBreak1 = py::class_<BreaksBase<1>, std::unique_ptr<BreaksBase<1>>, BreaksTramp<1>>;
491 using DoesntBreak2 = py::class_<BreaksBase<2>, BreaksTramp<2>, std::unique_ptr<BreaksBase<2>>>;
492 using DoesntBreak3 = py::class_<BreaksBase<3>, std::unique_ptr<BreaksBase<3>>>;
493 using DoesntBreak4 = py::class_<BreaksBase<4>, BreaksTramp<4>>;
494 using DoesntBreak5 = py::class_<BreaksBase<5>>;
495 using DoesntBreak6 = py::class_<BreaksBase<6>, std::shared_ptr<BreaksBase<6>>, BreaksTramp<6>>;
496 using DoesntBreak7 = py::class_<BreaksBase<7>, BreaksTramp<7>, std::shared_ptr<BreaksBase<7>>>;
497 using DoesntBreak8 = py::class_<BreaksBase<8>, std::shared_ptr<BreaksBase<8>>>;
498 #define CHECK_BASE(N) static_assert(std::is_same<typename DoesntBreak##N::type, BreaksBase<N>>::value, \
499 "DoesntBreak" #N " has wrong type!")
500 CHECK_BASE(1); CHECK_BASE(2); CHECK_BASE(3); CHECK_BASE(4); CHECK_BASE(5); CHECK_BASE(6); CHECK_BASE(7); CHECK_BASE(8);
501 #define CHECK_ALIAS(N) static_assert(DoesntBreak##N::has_alias && std::is_same<typename DoesntBreak##N::type_alias, BreaksTramp<N>>::value, \
502 "DoesntBreak" #N " has wrong type_alias!")
503 #define CHECK_NOALIAS(N) static_assert(!DoesntBreak##N::has_alias && std::is_void<typename DoesntBreak##N::type_alias>::value, \
504 "DoesntBreak" #N " has type alias, but shouldn't!")
505 CHECK_ALIAS(1); CHECK_ALIAS(2); CHECK_NOALIAS(3); CHECK_ALIAS(4); CHECK_NOALIAS(5); CHECK_ALIAS(6); CHECK_ALIAS(7); CHECK_NOALIAS(8);
506 #define CHECK_HOLDER(N, TYPE) static_assert(std::is_same<typename DoesntBreak##N::holder_type, std::TYPE##_ptr<BreaksBase<N>>>::value, \
507 "DoesntBreak" #N " has wrong holder_type!")
508 CHECK_HOLDER(1, unique); CHECK_HOLDER(2, unique); CHECK_HOLDER(3, unique); CHECK_HOLDER(4, unique); CHECK_HOLDER(5, unique);
509 CHECK_HOLDER(6, shared); CHECK_HOLDER(7, shared); CHECK_HOLDER(8, shared);
510
511 // There's no nice way to test that these fail because they fail to compile; leave them here,
512 // though, so that they can be manually tested by uncommenting them (and seeing that compilation
513 // failures occurs).
514
515 // We have to actually look into the type: the typedef alone isn't enough to instantiate the type:
516 #define CHECK_BROKEN(N) static_assert(std::is_same<typename Breaks##N::type, BreaksBase<-N>>::value, \
517 "Breaks1 has wrong type!");
518
519 //// Two holder classes:
520 //typedef py::class_<BreaksBase<-1>, std::unique_ptr<BreaksBase<-1>>, std::unique_ptr<BreaksBase<-1>>> Breaks1;
521 //CHECK_BROKEN(1);
522 //// Two aliases:
523 //typedef py::class_<BreaksBase<-2>, BreaksTramp<-2>, BreaksTramp<-2>> Breaks2;
524 //CHECK_BROKEN(2);
525 //// Holder + 2 aliases
526 //typedef py::class_<BreaksBase<-3>, std::unique_ptr<BreaksBase<-3>>, BreaksTramp<-3>, BreaksTramp<-3>> Breaks3;
527 //CHECK_BROKEN(3);
528 //// Alias + 2 holders
529 //typedef py::class_<BreaksBase<-4>, std::unique_ptr<BreaksBase<-4>>, BreaksTramp<-4>, std::shared_ptr<BreaksBase<-4>>> Breaks4;
530 //CHECK_BROKEN(4);
531 //// Invalid option (not a subclass or holder)
532 //typedef py::class_<BreaksBase<-5>, BreaksTramp<-4>> Breaks5;
533 //CHECK_BROKEN(5);
534 //// Invalid option: multiple inheritance not supported:
535 //template <> struct BreaksBase<-8> : BreaksBase<-6>, BreaksBase<-7> {};
536 //typedef py::class_<BreaksBase<-8>, BreaksBase<-6>, BreaksBase<-7>> Breaks8;
537 //CHECK_BROKEN(8);
538