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