Boost.Python:指针变量的所有权 [英] Boost.Python: Ownership of pointer variables
问题描述
我将使用Boost.Python的C ++树类公开给python.节点类包含子节点列表并提供方法
I'm exposing a C++ tree class using Boost.Python to python. The node class holds a list of child nodes and provides a method
void add_child(Node *node)
Node类获得所提供的Node指针的所有权,并在调用构造函数时删除其子节点.
The Node class takes ownership of the provided Node pointer and deletes it's child nodes when the destuctor gets called.
我将add_child方法公开为:
I'm exposing the add_child method as:
.def("addChild", &Node::add_child)
我的实际问题是:如何告诉Boost.Python Node类获得子节点的所有权?
My actual question is: How do i tell Boost.Python that the Node class takes ownership of the child nodes?
因为我是否在python中执行以下代码:
Because if i execute the following code in python:
parentNode = Node()
node = Node()
parentNode.addChild(node)
由节点变量引用的对象在脚本末尾被删除两次.一次在删除节点变量时,第二次在删除父节点时.
the object referenced by the node variable gets deleted twice at the end of the script. Once when the node variable gets deleted and a second time when the parentNode gets deleted.
推荐答案
回答我自己的问题:
我错过了Boost.Python文档中的FAQ条目,该条目为我提供了正确的提示:
I've missed an FAQ entry in the Boost.Python documentation that gave me the right hint:
//The node class should be held by std::auto_ptr
class_<Node, std::auto_ptr<Node> >("Node")
为add_child方法创建一个精简包装函数:
Create a thin wrapper function for the add_child method:
void node_add_child(Node& n, std::auto_ptr<Node> child) {
n.add_child(child.get());
child.release();
}
完成暴露节点类的代码:
Complete code to expose the node class:
//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)
;
这篇关于Boost.Python:指针变量的所有权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!