This is a newbe question but I have alwasy doubts with pointers in C++. This is the situation.
I have a class A which as a collection (a vector actually) of pointers of class B. This same class A has another collection of pointers to class C. Finally the objects of class B have also a collection to pointers to class C which point to the same instances the class A points to.
My question is, if I delete a member of class-C-type pointer in class B, what happens to the pointer in class A that points to the deleted instance of class C? How this situation has to be treated?
Thanks a lot in advance!
Julen.
My understanding:
A - vector<B*> - vector<C*> B - vector<C*>
From within B you are deleting all of the C*.
You need to delete each memory address separately, but only at most once.
Any pointer to a deleted address is still holding the same address, it just produces undefined behavior if you use it.
So be sure not to re-delete the B* from A that you already deleted, and be sure not to use them after they are deleted.
You may want to re-consider your hierarchy/design though.
Or consider using boost::shared_ptr if you need to store things in this way. Actually anytime you're storing a collection of pointers you should probably be using boost::shared_ptr. If you are using boost::shared_ptr you don't delete and you don't need to worry about invalidating the other pointers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With