C++中 auto_ptr和tr1::shared_ptr的区别

本文基于《EffectiveC++》一书中的智能指针部分,深入探讨了auto_ptr与shared_ptr的特性、使用场景及潜在问题,旨在帮助开发者更准确地掌握智能指针的正确应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近在看《Effective C++》这本书,上面看到了智能指针这一部分,看后很有感触,所以想把自己看到的写下来,加深一下印象

auto_ptr有一个不寻常的性质:若通过copy构造函数或者copy assignment操作复制它们,它们会变成null,而复制所得的指针将取得资源的唯一拥有权。

举个例子说明一下:

std::auto_ptr<A> pInv1(CreateInvestment());//pInv1指向CreateInvestment()返回物

std::auto_ptr<A> pInv2(pInv1);//现在pInv2指向对象,pInv为null

pInv2=pInv1;//现在pInv1指向对象,pInv2为空

A::A():_localint(0)
{


}


A::~A()
{


}


int _tmain(int argc, _TCHAR* argv[])
{
std::auto_ptr<A> ptr1(new A());
std::auto_ptr<A> ptr2(ptr1);


cout<<ptr2->_localint<<endl;
//cout<<ptr1->_localint<<endl;//执行到这的时候,程序会报错!


        ptr1 = ptr2;
cout<<ptr1->_localint<<endl;//程序又正常了
return 0;
}


这样指针在释放的时候,对象会被释放一次以上。所以要注意!!!

而tr1::shared_ptr可以将多个指针同时指向同一个对象。

若使用tr1::shared_ptr

tr1::shared_ptr<A> ptr1(new A());
tr1::shared_ptr<A> ptr2(ptr1);


cout<<ptr2->_localint<<endl;

cout<<ptr1->_localint<<endl;

程序正常通过!

使用std::shared_ptr可以获取对象。std::shared_ptr是一种智能指针,它可以记录多少个shared_ptr共同指向一个对象,并且在引用计数变为零的时候自动删除对象。在代码示例中,通过使用new关键字创建一个B类型的对象pint,并将其传递给std::tr1::shared_ptr<B>指针ptrB1ptrB2ptrB3。这样,这三个智能指针都指向了同一个B对象。通过调用use_count()方法可以获取当前指针的引用计数,即指向该对象的智能指针数量。在示例中,打印结果是1,表示有一个智能指针指向了这个对象。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [std::shared_ptr的使用](https://blog.youkuaiyun.com/lyshiba/article/details/124429390)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] - *3* [C++常用类 shared_ptr](https://blog.youkuaiyun.com/yang_chen_shi_wo/article/details/46808757)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值