effective c++ 条款13:以对象管理

记住:

  • 为防止资源泄漏,请使用RAII对象,它们在构造函数中获得资源并在析构函数中释放资源。
  • 两个常被使用的RAII类分别是tr1::shared_ptr和auto_ptr。前者通常是较佳选择,因为其copy行为比较直观。若选择auto_ptr,复制动作会使它(被复制物)指向null。
class Investment { ... };
Investment* createInvestment();

void f()
{
    Investment* pInv = createInvestment();
    ...     // 若这里return了或者发生异常了,会导致delete调用不到
    delete pInv;
}


使用auto_ptr解决

void f()
{
    std::auto_ptr<Investment> pInv(createInvestment());
    ... //经由auto_ptr的析构函数自动删除pInv
}

//为了防止对象被删除一次以上,auto_ptr有个特性:若通过拷贝构造函数或者拷贝赋值操作复制它们,它们会变成null,而复制所得的指针将取得资源的唯一拥有权。
std::auto_ptr<Investment> pInv1(createInvestment());
std::auto_ptr<Investment> pInv2(pInv1); //现在pInv2指向对象,pInv1为null
pInv1 = pInv2;                          //现在pInv1指向对象,pInv2为null


使用share_ptr解决

void f()
{
    ...
    std::tr1::shared_ptr<Investment> pInv(createInvestment());

    std::tr1::shared_ptr<Investment> pInv2(pInv1);  //pInv1和pInv2指向同一个对象
    pInv1 = pInv2;                                  //同上

    ... //经由shared_ptr的析构函数自动删除pInv1和pInv2指向的同一个对象
}


注意:
auto_ptr和tr1::shared_ptr两者都在其析构函数内做delete而不是delete[]操作。所以在动态分配而得到的array身上使用auto_ptr或tr1::shared_ptr是错误的。
比如:
std::auto_ptr<std::string> aps(new std::string[10]);
std::tr1::shared_ptr<int> spi(new int[1024]);




posted @ 2018-06-18 12:44  pfsi  阅读(121)  评论(0编辑  收藏  举报