#include <iostream> #include <memory> void fun(std::shared_ptr<int> sp) { std::cout << "in fun(): sp.use_count() == " << sp.use_count() << " (object @ " << sp << ")\n"; } int main() { auto sp1 = std::make_shared
返回管理当前对象的不同 shared_ptr 实例的数量(包含 *this)。若无管理对象,则返回 0。 多线程环境中,use_count 原子地获得实例的数量(典型实现使用 std::memory_order_release 加载)。 参数(无) 返回值管理当前对象的 std::shared_ptr 实例的数量,或若无被管理对象则为 0。
std::shared_ptr 是一种智能指针,它能够记录多少个 shared_ptr 共同指向一个对象,从而消除显示的调用 delete,当引用计数变为零的时候就会将对象自动删除。 std::shared_ptr 可以通过 get() 方法来获取原始指针,通过 reset() 来减少一个引用计数, 并通过use_count()来查看一个对象的引用计数。例如: auto pointe...
管理一个动态分配的整数 std::shared_ptr<int> ptr1 = std::make_shared<int>%2810%29; // 输出值和引用计数 std::cout << "值: " << %2Aptr1 << ", 引用计数: " << ptr1.use_count%28%29 << std::endl; { // 创建另一个 shared_ptr,指向相同的资源 std::shared...
引用计数:每一个std::shared_ptr对象都会维护一个引用计数。当创建新的std::shared_ptr指向相同对象时,引用计数增加;当某个std::shared_ptr被销毁时,引用计数减少。当引用计数为 0 时,std::shared_ptr会自动释放对象的内存。 可以通过use_count()获取当前的引用计数。
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'; ...
#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() << '...
use_count():返回当前共享对象的引用计数值。 reset():释放当前所拥有的对象(如果存在),可选地接受一个新的裸指针来接管。 get():返回指向对象的原始指针,但不改变所有权。 operator->() 和 operator*():提供对托管对象的直接访问。 swap():交换两个shared_ptr的内容。
C++ 11 模板库的 <memory> 头文件中定义的智能指针,即 shared_ptr 模板类,用来管理指针的存储,提供有限的内存回收函数,可同时与其他对象共享该管理功能,从而帮助彻底消除内存泄漏和悬空指针的问题。 shared_ptr 类型的对象能够获得指针的所有权并共享该所有权:一旦他们获得所有权,指针的所有者组就会在最后一个释放该...
void print(auto rem, std::shared_ptr<Base> const& sp) { std::cout << rem << "\n\tget() = " << sp.get() << ", use_count() = " << sp.use_count() << '\n'; } void thr(std::shared_ptr<Base> p) { std::this_thread::sleep_for(987ms); //线程睡眠987毫秒 ...