test_unique_ptr_member.cpp 1.72 KB
Newer Older
1
2
#include "pybind11_tests.h"

3
#include <pybind11/smart_holder.h>
4

5
6
7
8
9
10
#include <memory>

namespace pybind11_tests {
namespace unique_ptr_member {

class pointee { // NOT copyable.
11
public:
12
13
    pointee() = default;

14
    int get_int() const { return 213; }
15

16
private:
17
    pointee(const pointee &) = delete;
18
    pointee(pointee &&)      = delete;
19
20
21
22
    pointee &operator=(const pointee &) = delete;
    pointee &operator=(pointee &&) = delete;
};

23
24
25
26
inline std::unique_ptr<pointee> make_unique_pointee() {
    return std::unique_ptr<pointee>(new pointee);
}

27
class ptr_owner {
28
public:
29
30
    explicit ptr_owner(std::unique_ptr<pointee> ptr) : ptr_(std::move(ptr)) {}

31
32
    bool is_owner() const { return bool(ptr_); }

33
34
    std::unique_ptr<pointee> give_up_ownership_via_unique_ptr() { return std::move(ptr_); }
    std::shared_ptr<pointee> give_up_ownership_via_shared_ptr() { return std::move(ptr_); }
35

36
private:
37
38
39
    std::unique_ptr<pointee> ptr_;
};

40
41
42
} // namespace unique_ptr_member
} // namespace pybind11_tests

43
PYBIND11_CLASSH_TYPE_CASTERS(pybind11_tests::unique_ptr_member::pointee)
44
45
46
47

namespace pybind11_tests {
namespace unique_ptr_member {

48
TEST_SUBMODULE(unique_ptr_member, m) {
49
50
51
    py::class_<pointee, py::smart_holder>(m, "pointee")
        .def(py::init<>())
        .def("get_int", &pointee::get_int);
52

53
54
    m.def("make_unique_pointee", make_unique_pointee);

55
    py::class_<ptr_owner>(m, "ptr_owner")
56
        .def(py::init<std::unique_ptr<pointee>>(), py::arg("ptr"))
57
        .def("is_owner", &ptr_owner::is_owner)
58
59
        .def("give_up_ownership_via_unique_ptr", &ptr_owner::give_up_ownership_via_unique_ptr)
        .def("give_up_ownership_via_shared_ptr", &ptr_owner::give_up_ownership_via_shared_ptr);
60
61
62
63
}

} // namespace unique_ptr_member
} // namespace pybind11_tests