在开发类似树的数据结构时,我写了这样的内容:
#include <memory>
class Node: public std::enable_shared_from_this<Node> {
public:
void set_root(Node & n);
private:
std::shared_ptr<Node> root;
std::shared_ptr<Node> leaf;
};
void Node::set_root(Node & n) {
root = n.shared_from_this();
n.leaf = shared_from_this();
}
int main() {
Node n1, n2;
n1.set_root(n2);
}
代码使用clang编译,但会中断运行时间(“ libc ++ abi.dylib:以类型为std :: __ 1 :: bad_weak_ptr:bad_weak_ptr的未捕获异常终止)”为什么?
编辑因此,基于答案,我想出了一个似乎可行的版本:
#include <memory>
class Node;
typedef std::shared_ptr<Node> Node_SP;
class Node: public std::enable_shared_from_this<Node> {
public:
void set_root(Node & n);
private:
std::shared_ptr<Node> root;
std::shared_ptr<Node> leaf;
};
void Node::set_root(Node & n) {
root = n.shared_from_this();
n.leaf = shared_from_this();
}
int main() {
Node_SP n1 = std::shared_ptr<Node>(new Node);
Node_SP n2 = std::shared_ptr<Node>(new Node);
n1->set_root(*n2);
}
shared_ptr
假定对象是在堆上分配的,但是您已经在堆栈上分配了它。
请new
改用并shared_ptr
致电delete
给您。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句