test_smart_holder_poc.cpp 1.98 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
#include "pybind11_tests.h"

#include <pybind11/smart_holder_poc.h>

#include <iostream>
#include <string>

namespace pybind11_tests {
namespace smart_holder_poc {

inline void to_cout(std::string msg) { std::cout << msg << std::endl; }

13
14
15
16
17
template <typename T>
struct functor_builtin_delete {
  void operator()(T* ptr) { delete ptr; }
};

18
19
inline void exercise() {
  to_cout("");
20
  using pybindit::memory::smart_holder;
21
  {
22
    smart_holder hld;
23
24
25
26
27
28
29
30
31
32
33
34
35
    hld.from_raw_ptr_owned(new int(13));
    to_cout(hld.rtti_held->name());
    {
      std::shared_ptr<int> val = hld.as_shared_ptr<int>();
      to_cout(std::to_string(*val));
    }
    {
      std::unique_ptr<int> val(hld.as_raw_ptr_owned<int>());
      to_cout(std::to_string(*val));
    }
  }  // namespace ;
  {
    std::unique_ptr<int> val(new int(13));
36
    smart_holder hld;
37
38
39
40
41
    hld.from_raw_ptr_unowned(val.get());
    to_cout(std::to_string(*hld.as_raw_ptr_unowned<int>()));
  }
  {
    std::unique_ptr<int> val(new int(13));
42
    smart_holder hld;
43
44
45
46
    hld.from_unique_ptr(std::move(val));
    to_cout(std::to_string(*hld.as_raw_ptr_unowned<int>()));
  }
  {
47
    smart_holder hld;
48
49
    hld.from_raw_ptr_owned(new int(13));
    to_cout(std::to_string(*hld.as_unique_ptr<int>()));
50
51
  }
  {
52
    std::unique_ptr<int, functor_builtin_delete<int>> unq_ptr(new int(13));
53
    smart_holder hld;
54
55
56
57
58
59
60
    hld.from_unique_ptr_with_deleter(std::move(unq_ptr));
    to_cout(std::to_string(unq_ptr.get() == nullptr));
    to_cout(std::to_string(*hld.as_raw_ptr_unowned<int>()));
    auto unq_ptr_retrieved =
        hld.as_unique_ptr_with_deleter<int, functor_builtin_delete<int>>();
    to_cout(std::to_string(hld.vptr.get() == nullptr));
    to_cout(std::to_string(*unq_ptr_retrieved));
61
  }
62
63
64
65
66
67
  {
    std::shared_ptr<int> val(new int(13));
    smart_holder hld;
    hld.from_shared_ptr(val);
    to_cout(std::to_string(*hld.as_raw_ptr_unowned<int>()));
  }
68
69
70
71
72
73
}

TEST_SUBMODULE(smart_holder_poc, m) { m.def("exercise", exercise); }

}  // namespace smart_holder_poc
}  // namespace pybind11_tests