参考:http://thispointer.com/shared_ptr-binary-trees-and-the-problem-of-cyclic-references/
#include <memory>
#include <iostream>
#include <vector>
using namespace std;
class Node : public enable_shared_from_this<Node>
{
public:
typedef weak_ptr<Node> weak_NodePtr;
typedef shared_ptr<Node> NodePtr;
typedef shared_ptr<const Node> NodePtr_const;
Node(const string& name) : mName(name) {
cout << "==== Node() ===="<< endl;
}
~Node() {
cout << "==== ~Node() ====" << endl;
}
const string& name() const {
return mName;
}
void addChild(const NodePtr& node) {
node->mParent = shared_from_this();
mChilds.push_back(node);
}
NodePtr_const parent() const {
if (!mParent.lock())
return shared_from_this();
return mParent.lock();
}
private:
string mName;
weak_NodePtr mParent;
vector<NodePtr> mChilds;
};
typedef shared_ptr<Node> NodePtr;
typedef shared_ptr<const Node> NodePtr_const;
int main() {
NodePtr node0(new Node("node0"));
NodePtr node1(new Node("node1"));
NodePtr node2(new Node("node2"));
NodePtr node3(new Node("node3"));
node0->addChild(node1);
node1->addChild(node2);
node2->addChild(node3);
cout << node0->name() << "\'s parent is " << node0->parent()->name() << endl;
cout << node1->name() << "\'s parent is " << node1->parent()->name() << endl;
cout << node2->name() << "\'s parent is " << node2->parent()->name() << endl;
cout << node3->name() << "\'s parent is " << node3->parent()->name() << endl;
return 0;
}