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

看板C_and_CPP作者 (raison detre)時間14年前 (2011/09/16 12:05), 編輯推噓1(102)
留言3則, 2人參與, 最新討論串1/2 (看更多)
請問一下各位 小弟在使用 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/16 16:41, , 1F
1.pointer、reference才有dynamic polymorphism
09/16 16:41, 1F

09/16 16:41, , 2F
2、3.copy constructor
09/16 16:41, 2F

09/19 09:24, , 3F
謝謝指教^^
09/19 09:24, 3F
文章代碼(AID): #1ESii4qW (C_and_CPP)
文章代碼(AID): #1ESii4qW (C_and_CPP)