std::shared_ptr::use_count
long use_count() const; | | |
|---|
返回不同shared_ptr实例%28this包括%29管理当前对象。如果没有托管对象,0会被归还。
在多线程环境中,使用返回的值。[医]计数大约为%28,典型实现使用记忆[医]命令[医]放松加载%29。
参数
%280%29
返回值
的数目shared_ptr实例管理当前对象或0如果没有托管对象。
例外
noexcept规格:
noexcept
注记
常见用例包括。
- 与...比较
0.如果use_count返回零,共享指针为空空并且不管理对象%28,无论其存储的指针是否为空%29。但是,这在多线程环境中并不能得到保证。
- 与...比较
1.如果use_count返回1,没有其他所有者,这可能表明托管对象是安全的修改。成员函数unique()是为这个用例提供的。但是,这在多线程环境中并不能得到保证。
例
二次
#include <memory>
#include <iostream>
void fun(std::shared_ptr<int> sp)
{
std::cout << "fun: sp.use_count() == " << sp.use_count() << '\n';
}
int main()
{
auto sp1 = std::make_shared<int>(5);
std::cout << "sp1.use_count() == " << sp1.use_count() << '\n';
fun(sp1);
}二次
产出:
二次
sp1.use_count() == 1
fun: sp.use_count() == 2二次
另见
unique (deprecated) | checks whether the managed object is managed only by the current shared_ptr instance (public member function) |
|---|
© cppreference.com在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。
本文档系腾讯云开发者社区成员共同维护,如有问题请联系 cloudcommunity@tencent.com

