是否有可能 `shared_ptr::use_count() == 0` 和 `shared_ptr::get() != nullptr`?

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

来自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.

有没有可能shared_ptr::use_count() == 0shared_ptr::get() != nullptr

有什么例子可以证明这是真的吗?

如注释中所述,别名构造函数导致这种情况发生。

例如:

#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 对于 use_count()b.get() 是非空的。

请注意,float 不受 b 的生命周期管理并且已泄漏。