Effective C++ 条款13

使用对象管理资源

在利用对象指针的时候,最后需要删除对象指针,实现内存释放,但是有可能在最后的时候,coder忘记释放了。

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

有可能在delete之前,return了,所以解决这个问题,最好是在析构函数内释放,这样 标准库里的auto_ptr就起到作用,

void f()
{
  std::auto_ptr<Investment> pInv(createInvestment());  // call factory
                                                       // function
  ...                                                  // use pInv as
                                                       // before
}                                                      // automatically
                                                       // delete pInv via
                                                       // auto_ptr's dtor

不过要注意的一点就是,不能让多个 auto_ptr 指向同一个对象,否则一旦有一个auto_ptr被自动释放之后,对象就不存在了(未定义),不过放心,为了防止这个问题,auto_ptrs 具有不同寻常的特性:拷贝它们(通过拷贝构造函数或者拷贝赋值运算符)就是将它们置为空(拷贝的时候自动将被拷贝的指针置空)。

sstd::auto_ptr<Investment>                 // pInv1 points to the
  pInv1(createInvestment());              // object returned from
                                          // createInvestment

std::auto_ptr<Investment> pInv2(pInv1);   // pInv2 now points to the
                                          // object; pInv1 is now null

pInv1 = pInv2;                            // now pInv1 points to the
                                          // object, and pInv2 is null

 相对于 auto_ptrs,另一个可选方案是一个引用计数智能指针(reference-counting smart pointer, RCSP)。一个 RCSP 是一个智能指针,它能持续跟踪有多少对象指向一个特定的资源,并能够在不再有任何东西指向那个资源的时候删除它。

总结:

  • 为了防止资源泄漏,使用 RAII 对象,在 RAII 对象的构造函数中获得资源并在析构函数中释放它们。

  • 两个通用的 RAII 是 tr1::shared_ptr 和 auto_ptr。tr1::shared_ptr 通常是更好的选择,因为它的拷贝时的行为是符合直觉的。拷贝一个 auto_ptr 是将它置为空。

猜你喜欢

转载自blog.csdn.net/qq_31638535/article/details/88974537