Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force deleting std::shared_ptr in C++

According to the first answer in this article: Explicitly deleting a shared_ptr

Is it possible to force delete a std::shared_ptr and the object it manages like below code?

do {
    ptr.reset();
} while (!ptr.unique());

ptr.reset();  // To eliminate the last reference

Technically, this should try calling std::shared_ptr::reset if the pointer has more than 1 reference count, unless it reaches to one. Any thoughts on this?

like image 561
Reza Hajianpour Avatar asked Nov 28 '22 21:11

Reza Hajianpour


1 Answers

This code doesn't make any sense.

Once you reset ptr, it doesn't manage an object anymore. If ptr was the only shared_ptr sharing ownership, then you're done. If it wasn't... well, you don't have access to all those other ones. Calling reset() on a disengaged shared_ptr is effectively a noop - there's nothing more to reset.

Imagine a simple scenario:

std::shared_ptr<int> a = std::make_shared<int>(42);
std::shared_ptr<int> b = a; // a and b are sharing ownership of an int

do {
    a.reset();
} while (!a.unique());

The only way to reset b is to reset b - this code will reset a only, it cannot possibly reach b.

Also note that unique() was deprecated in C++17 and is removed entirely in C++20. But if even if you use use_count() instead, once you do a.reset(), a.use_count() will be equal to 0 because a no longer points to an object.

like image 128
Barry Avatar answered Dec 05 '22 20:12

Barry