Skip to content

Instantly share code, notes, and snippets.

@njlr
Created May 25, 2017 13:56
Show Gist options
  • Save njlr/b178eb9f18bd639223c70f6fa6b7e099 to your computer and use it in GitHub Desktop.
Save njlr/b178eb9f18bd639223c70f6fa6b7e099 to your computer and use it in GitHub Desktop.
struct Node {
string name;
weak_ptr<Node> parent;
vector<shared_ptr<Node>> children;
bool hasParent() {
return parent.expired();
}
shared_ptr<Node> getParent() {
return parent.lock();
// If hasParent() then return shared_ptr from parent else nullptr
}
Node& addChild(shared_ptr<Node> node) {
if(node.hasParent()) {
throw "node already belongs to a parent";
}
children.emplace_back(node);
node->parent = this;
return *this;
}
Node& removeChild(unsigned i) {
children[i].parent.reset(); // Remove parent;
children.erase(&children[i]);
return *this;
}
static shared_ptr<Node> create(string const& name) {
return make_shared<Node>(name);
}
};
shared_ptr<Node> createTree() {
shared_ptr<Node> root = Node::create("root");
shared_ptr<Node> foo = Node::create("foo");
shared_ptr<Node> bar = Node::create("bar");
shared_ptr<Node> baz = Node::create("baz");
root
->addChild(foo)
->addChild(bar);
bar->addChild(baz);
return root;
}
int main() {
auto tree = createTree();
auto baz = tree->children[1]->children[0];
tree->removeChild(1); // Remove bar
ASSERT(baz.hasParent() == false);
// If parent would be a shared_ptr,
// then bar and baz would keep eachother alive forever.
return 0;
}
@insanustu
Copy link

weak_ptr can't be initialized with a raw pointer as it is on line #20. This example isn't compiling.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment