Reputation: 1205
I have a vector of pointers to other "objects" in a class.
Is there any way, after/when one of those objects gets deleted to remove any pointer that might have been pointing to it from the vector?
The best thing would be to propagate the deletion somehow but, it would also be okay to just know an object has been deleted whenever the vector gets traversed.
Upvotes: 1
Views: 60
Reputation: 69663
Do not use vanilla pointers. Use the classes std::shared_ptr
and std::weak_ptr
instead.
These classes implement automatic memory management. When you don't need an object anymore, you don't delete the object, you delete all the shared_ptr
s which reference that object. Only when no shared_ptr
s to an object exist anymore, the actual object will get deleted.
Any weak_ptr
s which still exist will return an object which will evaluate as false
. When that happens, you know the weak_ptr
can be removed from the vector.
Upvotes: 1
Reputation: 179907
That's why std::weak_ptr
exists. It doesn't stop deletion, but it does detect it.
Upvotes: 1