Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible that `shared_ptr::use_count() == 0` and `shared_ptr::get() != nullptr`?

From the cppref:

Notes

An empty shared_ptr (where use_count() == 0) may store a
non-null pointer accessible by get(), e.g. if it were created using
the aliasing constructor.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is it possible that shared_ptr::use_count() == 0 and shared_ptr::get() != nullptr?

Any example to illustrate that is true?

>Solution :

As stated in the notes, the aliasing constructor causes this to happen.

For example:

#include <memory>
#include <iostream>

int main()
{
    std::shared_ptr<int> a = nullptr;
    std::shared_ptr<float> b(a, new float(0.0));
    std::cout << b.use_count() << "\n";
    std::cout << (b.get() == nullptr) << "\n";
}

prints 0 for the use_count() and b.get() is non-null.

Note that the float isn’t managed by the lifetime of b and is leaked.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading