2012-04-05 75 views
7

我有在異常類auto_ptr的一個問題,那我最終簡化爲:爲什麼我不能有一個異常類一個auto_ptr

#include <memory> 

class MyException 
{ 
    std::auto_ptr<int> m_foo2; 
}; 

int main() 
{ 
    try 
    { 
     throw MyException(); 
    } 
    catch (const MyException&) 
    { 

    } 
    return 0; 
} 

這失敗,編譯:

/perforce/unstable/test/Common/Exceptions/TestException4.cpp: In function 'int main()': /perforce/unstable/test/Common/Exceptions/TestException4.cpp:12: error: no matching function for call to 'MyException::MyException(MyException)' /perforce/unstable/test/Common/Exceptions/TestException4.cpp:4: note: candidates are: MyException::MyException() /perforce/unstable/test/Common/Exceptions/TestException4.cpp:4: note: MyException::MyException(MyException&) /perforce/unstable/test/Common/Exceptions/TestException4.cpp:12: error: in thrown expression

如果我刪除auto_ptr,錯誤消失。

這是因爲異常正在被複制或分配?在異常中有沒有使用auto_ptr的方法?

+0

哇,高質量的答案在這裏。一定是個好問題。 :) – sje397 2012-04-05 11:03:35

回答

9

Is this because the exception is being copied or assigned?

事實確實如此。本標準規定了一個例外是如何扔在C++ 11 15.1/3:

A throw-expression initializes a temporary object, [...]. The temporary is an lvalue and is used to initialize the variable named in the matching handler.

初始化與隱含的拷貝構造函數來完成。這被聲明爲MyException(MyException&),因爲有一個成員需要非const引用參數(如C++ 11 12.8/9中指定的)。臨時對象不能綁定到非const引用,所以構造失敗。

Is there a way of using auto_ptrs in an Exception?

如果你能使用C++ 11,那麼你可以使用unique_ptr代替,並委託auto_ptr歷史的深處。你的類將有一個隱含的移動構造函數,聲明爲MyException(MyException&&),它可以用來從臨時對其進行初始化。

否則,你可以拋出一個非暫時性的價值:

MyException ex; 
throw ex; 

,或者你可以砍你的類增加一個明確的拷貝構造函數和使用const_castmutable以允許以允許從const參考初始化複製auto_ptr - 但這是潛在的危險,我不會推薦它。

相關問題