Reputation: 1121
Consider the following code:
class Child {
vector<Object>::iterator it;
}
class Parent {
vector<Object> objects;
Child getChild(int idx) {
Child ret;
ret.it = objects.begin() + idx;
return ret;
}
}
Obviously the child must not outlive its parent, but I expect it to be reasonable to try to call something like Child childThing = getParent().getChild(5)
. How can I prevent this? Is there a pattern to enforce keeping an instance of Parent
around? If possible I don't want to copy objects
as its contents are quite complex.
Upvotes: 2
Views: 278
Reputation: 971
Having a child as a member of a parent would help you ensure that (specially if you don't hand out references to the child around and save them somewhere else). The principle is simple: the child is constructed inside the parent and it won't be destroyed until the parent is.
As for copying objects, you can always hand out references or pointers. There's no sizable copy penalty there.
In other order of things, iterators (as the one your child has) can easily be invalidated once the contents of their container changes, so I'd be wary of those.
Edit: After your comment, you could try to use a shared_ptr to refer to your parent objects. These will keep the parent alive while at least there's a child with them. std::shared_ptr are reference-counted and have a small overhead over a regular, unmanaged pointer. You could, for example, make a instance of your parent as a std::shared_ptr and then copy this pointer around on the children. Once all children and the parent themselves are out of scope, the parent will be deleted.
Upvotes: 1