C ++ sets all pointers to null when deleting an object through one of them

I have an object and there are many pointers referencing it. It can be deleted in different places, but once in one place it is deleted, other places should be aware of the deletion. Therefore, they must check if the object has been destroyed and then delete. Is there a smart pointer that can do the job?

+3


source to share


3 answers


std :: shared_ptr can do this along with std :: weak_ptr



I'll give you the Google syntax yourself, but basically the object that is stored in the shared_ptr gets deleted when the last shared_ptr goes out of scope, and any weak ptrs can detect this and stop working.

+6


source


A long time ago in a game I was working on, long before the C ++ standard introduced smart pointers outside of auto_ptr, we had something similar - NotadPointer<T>

. N ull O n Ta rget D Index estimate.

It was a smart pointer of sorts that automatically fetched any other pointers to an object when the object was deleted.



It did this by storing a linked list of all pointer instances and then skipping that list on destruction, destroying all of them. The pre-threading was actually pretty neat and worked well [moderately costly copy / create, but no overhead to actually dereference. The instance size was 3 pointers [prev / next / actual value].

However, in the brave new (ish) world of multithreading, its dangerous - zeroing out other pointers that are currently being used on another thread doesn't work well, so we ditched it for shared_ptr as things and friends that are multithreaded.

+1


source


Given your comments, I tend to believe your concept of ownership is wrong.

The definition of owner is that an object cannot be destroyed as long as it contains a reference. In your system, although they are all owners and observers at the same time, which is completely broken.

In the C ++ ownership model, object A owns resource B (including another object) if and only if resource B cannot be destroyed until A agrees. Otherwise, it is an observer. An object cannot be owned, nor can it have someone else destroying the object while he is still trying to use it. This is not the owner. Also, the observer cannot destroy the resource because it is not the owner. Only the owners of the resource can destroy it.

An object cannot be simultaneously an owner and an observer (of the same resource). It makes absolutely no sense.

If you want to share property, use shared_ptr

one that will handle you appropriately. If you want to know if it has been removed use weak_ptr

. Never delete an object under any circumstances, unless it shared_ptr

automatically clears it.

+1


source







All Articles