max
max

Reputation: 1057

determine if a std::shared_ptr is the unique reference to an object

Is there a way to ensure that a std::shared_ptr is the only reference to an object in the whole program?

I was under the impression that the following would be sufficient even in a multithreaded environment, but with std::shared_ptr::unique being deprecated I am not so sure (and my concurrent-fu fails me):

std::shared_ptr<Foo> bar(std::shared_ptr<Foo>&& src) {
     std::shared_ptr<Foo> self = std::move(src);
     if(self && self.unique()) {
        // self is *the* only reference
     }

     return std::move(self);
}

(edit)

If I understand correctly (see e.g. Why is std::shared_ptr::unique() deprecated?) the atomic ref-counting guarantees that self is the only live ref to the data inside the if block, but modifications through destructed references are not sequenced-before the call to unique() and may not have completed yet.

Henceforth, there is still a potential data race when modifying *self inside the if block. Is this correct?

Upvotes: 3

Views: 783

Answers (1)

yuri kilochek
yuri kilochek

Reputation: 13484

This is not sufficient because .unique() (and .use_count()) ignore any weak_ptrs linked to your shared_ptr, which can be .lock()ed concurrently, invalidating your assumptions.

Upvotes: 3

Related Questions