gpt4 book ai didi

c++ - 如果通过引用捕获异常,是否可以修改并重新抛出?

转载 作者:IT老高 更新时间:2023-10-28 21:51:11 25 4
gpt4 key购买 nike

该标准是否对通过引用捕获的异常以及修改它的尝试有什么要说明?

考虑以下代码:

class my_exception: public std::logic_error
{
public:
std::vector<std::string> callstack;
};

void MyFunc()
{
try
{
SomethingThatThrows();
}
catch (my_exception & e)
{
e.callstack.push_back("MyFunc");
throw;
}
}

这是一个人为的例子,我实际上并没有尝试这样的事情。我只是好奇会发生什么,基于另一个线程中的建议,异常应该由 const 引用捕获。

最佳答案

异常会改变。

§15.3[except.handle]/17:

When the handler declares a non-constant object, any changes to that object will not affect the temporary object that was initialized by execution of the throw-expression.

When the handler declares a reference to a non-constant object, any changes to the referenced object are changes to the temporary object initialized when the throw-expression was executed and will have effect should that object be rethrown.

因此,如果 my_exceptionMyFunc 之外被捕获,我们将在调用堆栈中看到 "MyFunc" 条目(例如 http://ideone.com/5ytqN )

关于c++ - 如果通过引用捕获异常,是否可以修改并重新抛出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8481147/

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