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.