The lifecycle of a Scope hierarchy
Created by: wangkuiyi
In class Scope
, there defines
private:
std::shared_ptr<Scope> parent_{nullptr};
This implies that the parent scope will be delete
d after all its children get destructed.
However, there could be difficulties with this design:
Delete a Scope instance on the stack
The parent Scope must not be allocated on the heap and don't need to be deleted at all!
Consider the following example:
Scope the_parent;
Scope* the_child = the_parent.NewScope();
delete the_child; // the destructor of the_child will try to delete the_parent, which, however is not on the heap and cannot be deleted at all.
Dangling parent pointer
Even if the parent is allocated on the heap, it can be deleted without following the constraint of scoped_ptr.
Scope* the_parent = new Scope;
Scope* the_child = the_parent.NewScope();
delete the_parent; // the_child.parent_ becomes a dangling pointer.
Solution
I think the right solution for a Scope hierarchy is pretty classical -- let the parent deletes all children at destruction time.