Re: [問題] std::exception 使用上的問題
感謝版友 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
09/20 14:37, 1F
→
09/20 14:38, , 2F
09/20 14:38, 2F
→
09/20 14:38, , 3F
09/20 14:38, 3F
→
09/20 15:11, , 4F
09/20 15:11, 4F
→
09/20 15:31, , 5F
09/20 15:31, 5F
→
09/20 15:32, , 6F
09/20 15:32, 6F
→
09/20 15:33, , 7F
09/20 15:33, 7F
→
09/20 16:45, , 8F
09/20 16:45, 8F
→
09/21 11:57, , 9F
09/21 11:57, 9F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):