Boost.Python: ownership of pointer variables

I am exposing a C ++ tree class using Boost.Python for python. The node class contains a list of child nodes and provides a method

void add_child(Node *node)

The node class takes responsibility for the provided node pointer and deletes its child nodes when destuctor is called.

I expose the add_child method as:

.def("addChild", &Node::add_child)

My real question is: how do I tell Boost.Python that the node class takes responsibility for the child nodes?

Because if I execute the following code in python:

parentNode = Node()
node = Node()
parentNode.addChild(node)

the object referenced by the node variable is deleted twice at the end of the script. Once, when the node variable is deleted, and a second time, when parentNode is deleted.

+3
source share
1

:

FAQ Boost.Python, :

//The node class should be held by std::auto_ptr
class_<Node, std::auto_ptr<Node> >("Node")

add_child:

void node_add_child(Node& n, std::auto_ptr<Node> child) {
   n.add_child(child.get());
   child.release();
}

, node:

//The node class should be held by std::auto_ptr
class_<Node, std::auto_ptr<Node> >("Node")
//expose the thin wrapper function as node.add_child()
.def("addChild", &node_add_child)
;
+4

Source: https://habr.com/ru/post/1773369/


All Articles