关于:C++ 中异常对象的范围:为什么我得不到副本?
about : Scope of exception object in C++ : why don't I get the copy?
问题about scope of exception是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
I would expect 2 copies to happen.
为什么? catch
块只复制了一份。第二个副本会在哪里发生?
set err_code to 1.1, but the display is still 1.
因为 get_code
returns 一个 int
,所以浮点值被截断了。
问题about scope of exception是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
I would expect 2 copies to happen.
为什么? catch
块只复制了一份。第二个副本会在哪里发生?
set err_code to 1.1, but the display is still 1.
因为 get_code
returns 一个 int
,所以浮点值被截断了。