blob: 6e8c9de363095be77681141ebcd92992fb23cd3f [file] [log] [blame]
Dean Moldovan67b52d82016-10-16 19:12:43 +02001Smart pointers
2##############
3
Dean Moldovan5d28dd12016-10-18 13:56:33 +02004std::unique_ptr
Dean Moldovan67b52d82016-10-16 19:12:43 +02005===============
6
7Given a class ``Example`` with Python bindings, it's possible to return
8instances wrapped in C++11 unique pointers, like so
9
10.. code-block:: cpp
11
12 std::unique_ptr<Example> create_example() { return std::unique_ptr<Example>(new Example()); }
13
14.. code-block:: cpp
15
16 m.def("create_example", &create_example);
17
18In other words, there is nothing special that needs to be done. While returning
19unique pointers in this way is allowed, it is *illegal* to use them as function
20arguments. For instance, the following function signature cannot be processed
21by pybind11.
22
23.. code-block:: cpp
24
25 void do_something_with_example(std::unique_ptr<Example> ex) { ... }
26
27The above signature would imply that Python needs to give up ownership of an
28object that is passed to this function, which is generally not possible (for
29instance, the object might be referenced elsewhere).
30
Dean Moldovan5d28dd12016-10-18 13:56:33 +020031std::shared_ptr
32===============
Dean Moldovan67b52d82016-10-16 19:12:43 +020033
34The binding generator for classes, :class:`class_`, can be passed a template
35type that denotes a special *holder* type that is used to manage references to
36the object. If no such holder type template argument is given, the default for
37a type named ``Type`` is ``std::unique_ptr<Type>``, which means that the object
38is deallocated when Python's reference count goes to zero.
39
40It is possible to switch to other types of reference counting wrappers or smart
41pointers, which is useful in codebases that rely on them. For instance, the
42following snippet causes ``std::shared_ptr`` to be used instead.
43
44.. code-block:: cpp
45
46 py::class_<Example, std::shared_ptr<Example> /* <- holder type */> obj(m, "Example");
47
48Note that any particular class can only be associated with a single holder type.
49
Dean Moldovan67b52d82016-10-16 19:12:43 +020050One potential stumbling block when using holder types is that they need to be
51applied consistently. Can you guess what's broken about the following binding
52code?
53
54.. code-block:: cpp
55
56 PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>);
57
58 class Child { };
59
60 class Parent {
61 public:
62 Parent() : child(std::make_shared<Child>()) { }
63 Child *get_child() { return child.get(); } /* Hint: ** DON'T DO THIS ** */
64 private:
65 std::shared_ptr<Child> child;
66 };
67
68 PYBIND11_PLUGIN(example) {
69 py::module m("example");
70
71 py::class_<Child, std::shared_ptr<Child>>(m, "Child");
72
73 py::class_<Parent, std::shared_ptr<Parent>>(m, "Parent")
74 .def(py::init<>())
75 .def("get_child", &Parent::get_child);
76
77 return m.ptr();
78 }
79
80The following Python code will cause undefined behavior (and likely a
81segmentation fault).
82
83.. code-block:: python
84
85 from example import Parent
86 print(Parent().get_child())
87
88The problem is that ``Parent::get_child()`` returns a pointer to an instance of
89``Child``, but the fact that this instance is already managed by
90``std::shared_ptr<...>`` is lost when passing raw pointers. In this case,
91pybind11 will create a second independent ``std::shared_ptr<...>`` that also
92claims ownership of the pointer. In the end, the object will be freed **twice**
93since these shared pointers have no way of knowing about each other.
94
95There are two ways to resolve this issue:
96
971. For types that are managed by a smart pointer class, never use raw pointers
98 in function arguments or return values. In other words: always consistently
99 wrap pointers into their designated holder types (such as
100 ``std::shared_ptr<...>``). In this case, the signature of ``get_child()``
101 should be modified as follows:
102
103.. code-block:: cpp
104
105 std::shared_ptr<Child> get_child() { return child; }
106
1072. Adjust the definition of ``Child`` by specifying
108 ``std::enable_shared_from_this<T>`` (see cppreference_ for details) as a
109 base class. This adds a small bit of information to ``Child`` that allows
110 pybind11 to realize that there is already an existing
111 ``std::shared_ptr<...>`` and communicate with it. In this case, the
112 declaration of ``Child`` should look as follows:
113
114.. _cppreference: http://en.cppreference.com/w/cpp/memory/enable_shared_from_this
115
116.. code-block:: cpp
117
118 class Child : public std::enable_shared_from_this<Child> { };
119
Dean Moldovan5d28dd12016-10-18 13:56:33 +0200120.. _smart_pointers:
121
122Custom smart pointers
123=====================
124
125pybind11 supports ``std::unique_ptr`` and ``std::shared_ptr`` right out of the
126box. For any other custom smart pointer, transparent conversions can be enabled
127using a macro invocation similar to the following. It must be declared at the
128level before any binding code:
129
130.. code-block:: cpp
131
132 PYBIND11_DECLARE_HOLDER_TYPE(T, SmartPtr<T>);
133
134The first argument of :func:`PYBIND11_DECLARE_HOLDER_TYPE` should be a
135placeholder name that is used as a template parameter of the second argument.
136Thus, feel free to use any identifier, but use it consistently on both sides;
137also, don't use the name of a type that already exists in your codebase.
Dean Moldovan67b52d82016-10-16 19:12:43 +0200138
139Please take a look at the :ref:`macro_notes` before using this feature.
140
141.. seealso::
142
143 The file :file:`tests/test_smart_ptr.cpp` contains a complete example
144 that demonstrates how to work with custom reference-counting holder types
145 in more detail.