sin*_*inθ 2 c++ binary-tree struct stl auto-ptr
有没有办法将auto_ptr设置为NULL或等效?例如,我正在创建一个由节点对象组成的二叉树:
struct Node {
int weight;
char litteral;
auto_ptr<Node> childL;
auto_ptr<Node> childR;
void set_node(int w, char l, auto_ptr<Node> L, auto_ptr<Node> R){
weight = w;
litteral = l;
childL = L;
childR = R;
}
};
Run Code Online (Sandbox Code Playgroud)
对于不是父节点的节点,我计划这样做:
auto_ptr<Node> n(new Node);
(*n).set_node(i->second, i->first, NULL, NULL);
Run Code Online (Sandbox Code Playgroud)
这会引发错误.有没有办法将它设置为NULL,还是有另一种有意义的行动方案?
std::auto_ptr
获取指针的构造函数是显式的,以帮助防止意外地将所有权转移到std::auto_ptr
.您可以传入两个默认构造的std::auto_ptr
对象:
(*n).set_node(i->second, i->first, std::auto_ptr<Node>(), std::auto_ptr<Node>());
Run Code Online (Sandbox Code Playgroud)
如果您要定位的标准库实现包括std::unique_ptr
,请考虑使用它.它没有有问题的复制语义std::auto_ptr
,因此std::auto_ptr
已被弃用并替换为std::unique_ptr
.
std::unique_ptr
还有一个转换构造函数,允许从空指针常量进行隐式转换,因此NULL
如果你使用的话,你的代码传递可以正常工作std::unique_ptr
.
归档时间: |
|
查看次数: |
1710 次 |
最近记录: |