Warning, /jana2/src/python/externals/pybind11-2.10.3/docs/advanced/smart_ptrs.rst is written in an unsupported language. File is not indexed.
0001 Smart pointers
0002 ##############
0003
0004 std::unique_ptr
0005 ===============
0006
0007 Given a class ``Example`` with Python bindings, it's possible to return
0008 instances wrapped in C++11 unique pointers, like so
0009
0010 .. code-block:: cpp
0011
0012 std::unique_ptr<Example> create_example() { return std::unique_ptr<Example>(new Example()); }
0013
0014 .. code-block:: cpp
0015
0016 m.def("create_example", &create_example);
0017
0018 In other words, there is nothing special that needs to be done. While returning
0019 unique pointers in this way is allowed, it is *illegal* to use them as function
0020 arguments. For instance, the following function signature cannot be processed
0021 by pybind11.
0022
0023 .. code-block:: cpp
0024
0025 void do_something_with_example(std::unique_ptr<Example> ex) { ... }
0026
0027 The above signature would imply that Python needs to give up ownership of an
0028 object that is passed to this function, which is generally not possible (for
0029 instance, the object might be referenced elsewhere).
0030
0031 std::shared_ptr
0032 ===============
0033
0034 The binding generator for classes, :class:`class_`, can be passed a template
0035 type that denotes a special *holder* type that is used to manage references to
0036 the object. If no such holder type template argument is given, the default for
0037 a type named ``Type`` is ``std::unique_ptr<Type>``, which means that the object
0038 is deallocated when Python's reference count goes to zero.
0039
0040 It is possible to switch to other types of reference counting wrappers or smart
0041 pointers, which is useful in codebases that rely on them. For instance, the
0042 following snippet causes ``std::shared_ptr`` to be used instead.
0043
0044 .. code-block:: cpp
0045
0046 py::class_<Example, std::shared_ptr<Example> /* <- holder type */> obj(m, "Example");
0047
0048 Note that any particular class can only be associated with a single holder type.
0049
0050 One potential stumbling block when using holder types is that they need to be
0051 applied consistently. Can you guess what's broken about the following binding
0052 code?
0053
0054 .. code-block:: cpp
0055
0056 class Child { };
0057
0058 class Parent {
0059 public:
0060 Parent() : child(std::make_shared<Child>()) { }
0061 Child *get_child() { return child.get(); } /* Hint: ** DON'T DO THIS ** */
0062 private:
0063 std::shared_ptr<Child> child;
0064 };
0065
0066 PYBIND11_MODULE(example, m) {
0067 py::class_<Child, std::shared_ptr<Child>>(m, "Child");
0068
0069 py::class_<Parent, std::shared_ptr<Parent>>(m, "Parent")
0070 .def(py::init<>())
0071 .def("get_child", &Parent::get_child);
0072 }
0073
0074 The following Python code will cause undefined behavior (and likely a
0075 segmentation fault).
0076
0077 .. code-block:: python
0078
0079 from example import Parent
0080
0081 print(Parent().get_child())
0082
0083 The problem is that ``Parent::get_child()`` returns a pointer to an instance of
0084 ``Child``, but the fact that this instance is already managed by
0085 ``std::shared_ptr<...>`` is lost when passing raw pointers. In this case,
0086 pybind11 will create a second independent ``std::shared_ptr<...>`` that also
0087 claims ownership of the pointer. In the end, the object will be freed **twice**
0088 since these shared pointers have no way of knowing about each other.
0089
0090 There are two ways to resolve this issue:
0091
0092 1. For types that are managed by a smart pointer class, never use raw pointers
0093 in function arguments or return values. In other words: always consistently
0094 wrap pointers into their designated holder types (such as
0095 ``std::shared_ptr<...>``). In this case, the signature of ``get_child()``
0096 should be modified as follows:
0097
0098 .. code-block:: cpp
0099
0100 std::shared_ptr<Child> get_child() { return child; }
0101
0102 2. Adjust the definition of ``Child`` by specifying
0103 ``std::enable_shared_from_this<T>`` (see cppreference_ for details) as a
0104 base class. This adds a small bit of information to ``Child`` that allows
0105 pybind11 to realize that there is already an existing
0106 ``std::shared_ptr<...>`` and communicate with it. In this case, the
0107 declaration of ``Child`` should look as follows:
0108
0109 .. _cppreference: http://en.cppreference.com/w/cpp/memory/enable_shared_from_this
0110
0111 .. code-block:: cpp
0112
0113 class Child : public std::enable_shared_from_this<Child> { };
0114
0115 .. _smart_pointers:
0116
0117 Custom smart pointers
0118 =====================
0119
0120 pybind11 supports ``std::unique_ptr`` and ``std::shared_ptr`` right out of the
0121 box. For any other custom smart pointer, transparent conversions can be enabled
0122 using a macro invocation similar to the following. It must be declared at the
0123 top namespace level before any binding code:
0124
0125 .. code-block:: cpp
0126
0127 PYBIND11_DECLARE_HOLDER_TYPE(T, SmartPtr<T>);
0128
0129 The first argument of :func:`PYBIND11_DECLARE_HOLDER_TYPE` should be a
0130 placeholder name that is used as a template parameter of the second argument.
0131 Thus, feel free to use any identifier, but use it consistently on both sides;
0132 also, don't use the name of a type that already exists in your codebase.
0133
0134 The macro also accepts a third optional boolean parameter that is set to false
0135 by default. Specify
0136
0137 .. code-block:: cpp
0138
0139 PYBIND11_DECLARE_HOLDER_TYPE(T, SmartPtr<T>, true);
0140
0141 if ``SmartPtr<T>`` can always be initialized from a ``T*`` pointer without the
0142 risk of inconsistencies (such as multiple independent ``SmartPtr`` instances
0143 believing that they are the sole owner of the ``T*`` pointer). A common
0144 situation where ``true`` should be passed is when the ``T`` instances use
0145 *intrusive* reference counting.
0146
0147 Please take a look at the :ref:`macro_notes` before using this feature.
0148
0149 By default, pybind11 assumes that your custom smart pointer has a standard
0150 interface, i.e. provides a ``.get()`` member function to access the underlying
0151 raw pointer. If this is not the case, pybind11's ``holder_helper`` must be
0152 specialized:
0153
0154 .. code-block:: cpp
0155
0156 // Always needed for custom holder types
0157 PYBIND11_DECLARE_HOLDER_TYPE(T, SmartPtr<T>);
0158
0159 // Only needed if the type's `.get()` goes by another name
0160 namespace PYBIND11_NAMESPACE { namespace detail {
0161 template <typename T>
0162 struct holder_helper<SmartPtr<T>> { // <-- specialization
0163 static const T *get(const SmartPtr<T> &p) { return p.getPointer(); }
0164 };
0165 }}
0166
0167 The above specialization informs pybind11 that the custom ``SmartPtr`` class
0168 provides ``.get()`` functionality via ``.getPointer()``.
0169
0170 .. seealso::
0171
0172 The file :file:`tests/test_smart_ptr.cpp` contains a complete example
0173 that demonstrates how to work with custom reference-counting holder types
0174 in more detail.