Re: [問題] std::exception 使用上的問題

看板C_and_CPP作者 (raison detre)時間14年前 (2011/09/20 13:58), 編輯推噓1(108)
留言9則, 3人參與, 最新討論串2/2 (看更多)
感謝版友 hilorrk 的解答 Q1: pointer、reference才有dynamic polymorphism Q2、Q3: copy constructor 但是這樣我卻衍生出了另外一個問題 為什麼pass by reference的狀況下 會呼叫到 copy constructor ※ 引述《ireullin (raison detre)》之銘言: : 請問一下各位 : 小弟在使用 std::exception 有一些疑問想請教一下 : 以下是我的程式碼 : class Print : { : private: : std::string m_fun; : public: : Print(const std::string& fun){m_fun=fun; std::cout << "Enter " << m_fun << : std::endl; } : ~Print(){ std::cout << "Leave " << m_fun << std::endl; } : }; : #define PRINT Print _P_(__FUNCTION__) : class TestException : public std::exception : { : private: : std::string m_errmsg; : public: : TestException() : { : PRINT; : m_errmsg = "TestException"; : } : virtual ~TestException()throw() : {PRINT;} : virtual const char* what() const throw() : {return m_errmsg.c_str();} : }; : 如果我的main寫成這樣的時候 : void Fun1() : { : TestException _exp; : throw _exp; : } : int main(int cnt, char** params) : { : try{Fun1();} : catch(std::exception exp) : {std::cout << exp.what() << std::endl;} : return 0; : } : 輸出結果是 : Enter TestException : Leave TestException : Enter ~TestException : Leave ~TestException : std::exception : Enter ~TestException : Leave ~TestException : 當我的main寫成這樣時 : void Fun1() : { : TestException _exp; : throw _exp; : } : int main(int cnt, char** params) : { : try{Fun1();} : catch(std::exception& exp) : {std::cout << exp.what() << std::endl;} : return 0; : } : 輸出結果是 : Enter TestException : Leave TestException : Enter ~TestException : Leave ~TestException : TestException : Enter ~TestException : Leave ~TestException : 我的問題是 : 1. 為何第一個方法輸出的結果是 std::exception 而不是 TestException : 照理說Fun1 中的_exp被拋出的時候應該是被複製了一份,只是catch抓到的時候才轉型為 : std::exception : 所以結果應該還是TestException : 2. 為何可以使用pass by reference 照理說 _exp 離開Fun1的時候就被消滅了 : 3. 為何TestException的解構式被呼叫了兩次 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 61.220.71.34

09/20 14:37, , 1F
兩件事是無關的 exp 參考到的是複製出來的例外物件
09/20 14:37, 1F

09/20 14:38, , 2F
_exp 已經在離開函式時銷毁了
09/20 14:38, 2F

09/20 14:38, , 3F
那為了要把這個例外物件丟出來才需要 copy ctor
09/20 14:38, 3F

09/20 15:11, , 4F
謝謝樓上
09/20 15:11, 4F

09/20 15:31, , 5F
more effective c++第12條中有說明,throw出的objects
09/20 15:31, 5F

09/20 15:32, , 6F
一定會被複製,因此會啟動copy ctor.你可以看_exp和exp
09/20 15:32, 6F

09/20 15:33, , 7F
位置是不同的喔.
09/20 15:33, 7F

09/20 16:45, , 8F
補充一點,你沒寫copy ctor,因此後面只出現~TestExc...
09/20 16:45, 8F

09/21 11:57, , 9F
謝謝你們的解答....我完全了解了^^
09/21 11:57, 9F
文章代碼(AID): #1EU2joPS (C_and_CPP)
文章代碼(AID): #1EU2joPS (C_and_CPP)