#include <iostream>
#include <memory>
int main()
{
//初始化p1
std::shared_ptr<int> p1 = std::make_shared<int>();
*p1 = 34;
std::cout << "p1 = " << *p1 << std::endl;
//打印引用个数:1
std::cout << "p1 reference count: " << p1.use_count() << std::endl;
//第二个 shared_ptr 对象指向同一个指针
std::shared_ptr<int> p2(p1);
//打印引用个数:都是2
std::cout << "p1 reference count: " << p1.use_count() << std::endl;
std::cout << "p2 reference count: " << p2.use_count() << std::endl;
//p1 等于 p2
if(p1 == p2) std::cout << "p1 == p2" << std::endl;
//无参数调用reset,无关联指针,引用个数为0
p1.reset();
std::cout << "p1 reference count: " << p1.use_count() << std::endl;
//带参数调用reset,引用个数为1
p1.reset(new int(11));
std::cout << "p1 reference count: " << p1.use_count() << std::endl;
//把对象置为NULL,引用个数为0
p1 = nullptr;
if(!p1) std::cout << "p1 is null" << std::endl;
return 0;
}
shared_ptr
最新推荐文章于 2024-06-15 20:01:32 发布