分享

C++使用对象来管理动态分配资源

 心不留意外尘 2016-04-23

from http://blog.csdn.net/stevenliyong/article/details/3728204

2009.01

C++使用对象来管理动态分配资源

1. 引入
void f()
{
  Investment *pInv = createInvestment();         // call factory function
  ...                                            // use pInv
  delete pInv;                                   // release object
}

代码本身没有问题,但这个存在隐患,程序员必须很小心的处理delete 才不至于出现内存泄露.
因为有可能在这个函数的 "..." 部分的某处有一个提前出现的 return 语句。
万一这样一个 return 被执行,就内存泄露了。

为了确保 createInvestment 返回的资源总能被释放,
我们可以将createInvestment 指针放入一个资源管理对象的实例中,
利用这个对象的析构函数来释放资源。
由于这个对象是存在栈上的,因此f()函数返回的时候
必然会调用对象析构函数来自动释放资源.


2. 使用auto_ptr对象
void f()
{
  std::auto_ptr<Investment> pInv(createInvestment());  // call factory
                                                       // function
  ...                                                  // use pInv as
                                                       // before
}          

但是存在问题,auto_ptr 只允许一个auto_prt对象指向Investment资源
因此拷贝构造函数和赋值操作都会使原来的指针为空
std::auto_ptr<Investment> pInv2(pInv1);   //pInv1 will be null !!!
pInv2 = pInv1;                            //pInv1 wiil be null !!!

正因为如此 auto_ptrs 的STL容器是不被允许的。


3.使用TR1的shared_ptr对象

tr1::shared_ptr能持续跟踪有多少 objects(对象)指向一个特定的资源,
并能够在不再有任何东西指向那个资源的时候自动删除它的 smart pointer(智能指针)。

std::tr1::shared_ptr<Investment>          // pInv1 points to the
    pInv1(createInvestment());              // object returned from
                                            // createInvestment

  std::tr1::shared_ptr<Investment>          // both
pInv1 and pInv2 now
    pInv2(pInv1);                           // point to the object

  pInv1 = pInv2;                            // ditto — nothing has
                                            // changed

tr1::shared_ptrs 能被用于 STL容器以及其它和 auto_ptr 的非正统的拷贝行为不相容的环境中。


3. 动态分配数组问题
但碰到动态分配数组的时候前述的两者都不是好主意

std::auto_ptr<std::string>                       // bad idea! the wrong
  aps(new std::string[10]);                      // delete form will be used

std::tr1::shared_ptr<int> spi(new int[1024]);    // same problem

这样的使用会导致auto_ptr或tr1::shared_ptr只删除一个string和int对象,而不是对象的数组引起内存泄露
(auto_ptr 或 tr1::shared_ptr 根本无法判断它指向的资源是一个单一的对象还是一个对象数组).

C++ 甚至在 TR1 都没有可用于动态分配数组的类似auto_ptr或tr1::shared_ptr这样的东西。
那是因为 vector几乎总是能代替动态分配数组!!! 汗.以后写C++代码的时候注意尽量用vector代替数组.

如果非要对动态分配数组资源使用对象管理,可以用boost库中的 boost::scoped_array 和 boost::shared_array 函数.

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多