|
| 1 | +#include "pybind11_tests.h" |
| 2 | + |
| 3 | +#include <memory> |
| 4 | + |
| 5 | +namespace pybind11_tests { |
| 6 | +namespace unique_ptr_member { |
| 7 | + |
| 8 | +class pointee { // NOT copyable. |
| 9 | + public: |
| 10 | + pointee() = default; |
| 11 | + |
| 12 | + int get_int() const { return 213; } |
| 13 | + |
| 14 | + private: |
| 15 | + pointee(const pointee &) = delete; |
| 16 | + pointee(pointee &&) = delete; |
| 17 | + pointee &operator=(const pointee &) = delete; |
| 18 | + pointee &operator=(pointee &&) = delete; |
| 19 | +}; |
| 20 | + |
| 21 | +class ptr_owner { |
| 22 | + public: |
| 23 | + explicit ptr_owner(std::unique_ptr<pointee> ptr) : ptr_(std::move(ptr)) {} |
| 24 | + |
| 25 | + private: |
| 26 | + std::unique_ptr<pointee> ptr_; |
| 27 | +}; |
| 28 | + |
| 29 | +// Just to have a minimal example of a typical C++ pattern. |
| 30 | +inline int cpp_pattern() { |
| 31 | + auto obj = std::unique_ptr<pointee>(new pointee); |
| 32 | + int result = (obj ? 10 : 0); |
| 33 | + ptr_owner owner(std::move(obj)); |
| 34 | + result += (obj ? 1 : 0); |
| 35 | + return result; |
| 36 | +} |
| 37 | + |
| 38 | +TEST_SUBMODULE(unique_ptr_member, m) { |
| 39 | + m.def("cpp_pattern", cpp_pattern); |
| 40 | + |
| 41 | + py::class_<pointee>(m, "pointee") |
| 42 | + .def(py::init<>()) |
| 43 | + .def("get_int", &pointee::get_int); |
| 44 | + |
| 45 | + py::class_<ptr_owner>(m, "ptr_owner") |
| 46 | +#ifdef FEAT_UNIQUE_PTR_ARG |
| 47 | + .def(py::init<std::unique_ptr<pointee>>(), py::arg("ptr")) |
| 48 | +#endif |
| 49 | + ; |
| 50 | +} |
| 51 | + |
| 52 | +} // namespace unique_ptr_member |
| 53 | +} // namespace pybind11_tests |
0 commit comments