1. 程式人生 > >effective c++ 條款13:以對象管理

effective c++ 條款13:以對象管理

行為 fec ret 拷貝構造函數 AR clas 釋放 AS RR

記住:

  • 為防止資源泄漏,請使用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]);




effective c++ 條款13:以對象管理