提问者:小点点

about:C++中异常对象的作用域:为什么我不获取副本?


关于例外范围的问题,AJ指出。 throw和catch子句将创建异常的副本(我猜除非使用引用)

我试了自己一个小玩具代码,我不明白结果。 此处:

//g++  7.4.0
#include <iostream>
using namespace std;
struct Some_error {
    Some_error(float code):err_code(code){ cout << "Some_error(" << err_code << ")\n";  }
    ~Some_error()                        { cout << "~Some_error(" << err_code << ")\n"; }
    Some_error(const Some_error& o):err_code(o.err_code+0.1)      { cout << "Some_error(copy::" << err_code << ")\n";  }
    Some_error(Some_error&& o):err_code(std::move(o.err_code)+.01){ cout << "Some_error(move::" << err_code << ")\n";  }
    int get_code() const { return err_code; }
    private : float err_code;
};

int do_task() { 
    if ( false )  return 42; else throw Some_error {1};
    cout << "end do_task\n" ;
}


void taskmaster(){
    try { auto result = do_task(); cout << "the answer is " << result << "\n" ; }
    catch (Some_error e) { cout << "catch Some_error : " << e.get_code() << "\n" ; }
    cout << "end taskmaster\n" ;
}

int main() { taskmaster(); }

我得到的轨迹如下:

Some_error(1)
Some_error(copy::1.1)
catch Some_error : 1
~Some_error(1.1)
~Some_error(1)
end taskmaster

现在首先,因为我在这里没有引用,根据AJ.,我预计会发生2个副本。

第二,有一个副本,它将err_code设置为1.1,但显示仍然是1。

备注:为了完整起见,我将catch更改为:catch(some_error&e),然后跟踪看起来很好:

Some_error(1)
catch Some_error : 1
~Some_error(1)
end taskmaster

共1个答案

匿名用户

我会期待2份副本发生。

为什么? catch块只进行一次复制。 第二个副本会发生在哪里?

将err_code设置为1.1,但显示仍为1。

因为get_code返回一个int,所以浮点值被截断。

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(c++|中|异常|对象|作用|域|获取|副本)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?