Serge Profafilecebook
Serge Profafilecebook

Reputation: 1205

How to have deletion of a object propagated or detected?

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

Answers (2)

Philipp
Philipp

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_ptrs which reference that object. Only when no shared_ptrs to an object exist anymore, the actual object will get deleted.

Any weak_ptrs 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

MSalters
MSalters

Reputation: 179907

That's why std::weak_ptr exists. It doesn't stop deletion, but it does detect it.

Upvotes: 1

Related Questions