C++智能指针之boost

参考文献:https://www.codeproject.com/Articles/8394/Smart-Pointers-to-boost-your-code

std:: auto_ptr中的智能指针有如下缺点:

(1)auto_ptr不能共享所有权;
(2)auto_ptr不能指向数组;
(3)auto_ptr不能作为容器的成员;
(4)不能通过赋值操作来初始化auto_ptr;
               std::auto_ptr<int>p(new int(42));     //OK
               std::auto_ptr<int>p = new int(42);    //ERROR

(5)不要把auto_ptr放入容器。

所以如果需要使用智能指针,推荐使用boost库中的智能指针:

scoped_ptr

<boost/scoped_ptr.hpp>

简单的单一对象的唯一所有权。不可拷贝。

scoped_array

<boost/scoped_array.hpp>

简单的数组的唯一所有权。不可拷贝。

shared_ptr

<boost/shared_ptr.hpp>

在多个指针间共享的对象所有权。

shared_array

<boost/shared_array.hpp>

在多个指针间共享的数组所有权。

weak_ptr

<boost/weak_ptr.hpp>

一个属于 shared_ptr 的对象的无所有权的观察者。

intrusive_ptr

<boost/intrusive_ptr.hpp>

带有一个侵入式引用计数的对象的共享所有权。

 智能指针scoped的使用:

void Sample1_Plain()
{
  CSample * pSample(new CSample);

  if (!pSample->Query() )
  // just some function...
  {
    delete pSample;
    return;
  }

  pSample->Use();
  delete pSample;
}
#include "boost/smart_ptr.h"

void Sample1_ScopedPtr()
{
  boost::scoped_ptr<CSample> samplePtr(new CSample);

  if (!samplePtr->Query() )
  // just some function...
    return;    

  samplePtr->Use();
}
智能指针shared 的使用:
void Sample2_Shared()
{
  // (A) create a new CSample instance with one reference
  boost::shared_ptr<CSample> mySample(new CSample); 
  printf("The Sample now has %i references\n", mySample.use_count()); // should be 1

  // (B) assign a second pointer to it:
  boost::shared_ptr<CSample> mySample2 = mySample; // should be 2 refs by now
  printf("The Sample now has %i references\n", mySample.use_count());

  // (C) set the first pointer to NULL
  mySample.reset(); 
  printf("The Sample now has %i references\n", mySample2.use_count());  // 1

  // the object allocated in (1) is deleted automatically
  // when mySample2 goes out of scope
}








      Boost库中的智能指针是通过引用计数值来确定对象是否应该被释放。强引用是当引用对象活着时,这引用也存在,shared_ptr就是强引用;而弱引用的引用对象活着时不一定存在,不修改引用计数值,只是普通的指针,但弱引用能检查对象是否已经被释放,避免访问非法内存。


      boost::weak_ptr必须从一个boost::share_ptr或另一个boost::weak_ptr转换而来,当对象存在循环引用时,引用计数值为1,也就存在无法释放内存的问题,采用弱指针可以解决该问题,弱指针不更改引用计数,只需将循环引用的一方使用弱引用即可:

typedef boost::shared_ptr<parent> parent_ptr;
typedef boost::shared_ptr<children> children_ptr;
class parent  {
children_ptr children;
};
class children  {
parent_ptr parent;
};
class children  {
    boost::weak_ptr<parent> parent;
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值