pepece
pepece

Reputation: 370

shared_ptr object global deletion

I wanted to use a smart pointer like shared_ptr of std library but where it would be possible to delete the object for every shared_ptr that share it without deleting those pointers.

For example if i use std::shared_ptr

shared_ptr<A> p1 = make_share<A>();
shared_ptr<A> p2 = shared_ptr<A>(p1);
p1.reset();
// now p2 still contain the object of type A
// instead of nullptr

Is there a way to do that or does some alternatives exist? Am i doing it wrong?

Upvotes: 0

Views: 635

Answers (1)

Quentin
Quentin

Reputation: 63124

Absolutely. std::shared_ptr comes with std::weak_ptr, a pointer that can point to an object managed by a set of std::shared_ptrs and check whether it is still alive, but does not extends the object's lifetime.

You just have to keep the original std::shared_ptr to your object, and lend std::weak_ptrs to other users of that object. When the object must be destroyed, reset the std::shared_ptr, and all remaining std::weak_ptrs will be able to tell (they'll return null std::shared_ptrs when the users try to lock them).

Upvotes: 3

Related Questions