gpt4 book ai didi

c++ - 按值或引用抛出异常

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:18:07 24 4
gpt4 key购买 nike

来自这个答案https://stackoverflow.com/a/36738405/4523099 :

A throw-expression with no operand rethrows the currently handled exception. The exception is reactivated with the existing temporary; no new temporary exception object is created. -- ISO/IEC 14882:2011 Section 15.1 par. 8

那么为什么我会从这段代码中得到这个结果?

代码:

#include <iostream>

class my_exception: public std::exception{
public:
int value;
};
int main()
{
my_exception ex;
ex.value=1;
try{
throw ex;
}
catch(my_exception& e){
e.value=2;
}
std::cout << ex.value;
return 0;
}

实际结果:

1

根据标准配额,我认为应该是2。我错过了什么?

最佳答案

这是因为 throw(普通版)会 make a copy :

First, copy-initializes the exception object from expression (this may call the move constructor for rvalue expression, and the copy/move may be subject to copy elision), ...

并将其保留在内部,因此 e.value=2; 修改内部拷贝。

在 SO 中,您提到的问题是关于重新抛出版本的女巫不制作新拷贝而是使用已经存在的内部拷贝。

关于c++ - 按值或引用抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36738607/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com