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

Time:11-26

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.

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

Any example to illustrate that is true?

CodePudding user response:

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.

  • Related