[英]Is it possible that `shared_ptr::use_count() == 0` and `shared_ptr::get() != nullptr`?
Notes笔记
An empty shared_ptr (where use_count() == 0) may store a non-null pointer accessible by get(), eg if it were created using the aliasing constructor.一个空的 shared_ptr(其中 use_count() == 0)可以存储一个可由 get() 访问的非空指针,例如,如果它是使用别名构造函数创建的。
Is it possible that shared_ptr::use_count() == 0
and shared_ptr::get() != nullptr
?是否可能shared_ptr::use_count() == 0
和shared_ptr::get() != nullptr
?
Any example to illustrate that is true?有什么例子可以说明这是真的吗?
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.为use_count()
打印0
并且b.get()
是非空的。
Note that the float
isn't managed by the lifetime of b
and is leaked.请注意, float
不受b
的生命周期管理并且被泄露。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.