Would it be smart to have a vector in an object with a list of pointers that point to it?
This way when the object is deleted, it could delete all the pointers pointing to it to prevent a null-pointer exception?
Would it be smart to have a vector in an object with a list of pointers that point to it?
This way when the object is deleted, it could delete all the pointers pointing to it to prevent a null-pointer exception?
No, definitely not. You can only delete a pointer to something once; freeing something that's already been deleted ("double-freeing") is undefined
A* foo = new A();
A* bar = foo;
delete foo;
delete foo; // <-- BAD
delete bar; // <-- EQUALLY BAD
It sounds like you're looking for something like auto_ptr; you might want to look into that. If you're looking to zero all pointers that point to your object when it's destroyed, there's no way of doing that
I don't really understand what you want to achieve, but deleting x times the same pointer won't get you far...
If you want to avoid having bad pointers after a delete
hapenned, you should look at smart pointers, and in particular boost::shared_ptr
.
The object pointed to is guaranteed to be deleted when the last shared_ptr pointing to it is destroyed or reset.
Using it you no longer have to manually delete
the pointers, the shared_ptr
does it by itself.
As a general help to work with pointer you might want to check out other boosts smart pointers or std::auto_ptr
Technically speaking, the problem you are trying to solve are "dangling pointers". Have a look at auto_ptr and also search for "smart pointers"... at least I suppose your intention is to zero out all pointers pointing to your object.
It is very hard or at least weird that every function using your objects also provides the address of where it is stored. It is hard those objects and pointers can be copied outside of your control (even more easy with a memcpy)
Some tools like valgrind can help you with that too
If your ultimate goal is to detect when an object is freed from users of the object the best bet is to use a weak pointer semantic. There an implementation in the Boost Smart Pointer library (see weak_ptr). It solves the problem you describe by reversing the reference graph you describe. It has the pointers reference a single common counter instance which when the originator deletes the object it sets to zero. Hence because all the weak_ptr references point to the single counter they all see the change immediately and hence you can tell when the object goes away.