按值或引用抛出异常

Throw exception by value or reference

从这个回答 :

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 中,您提到的问题是关于重新抛出版本的 不会制作新副本,而是使用已经存在的内部副本。

只有重新抛出(没有操作数)才会重复使用同一个异常对象。下面是一些代码来证明这一点:

#include <iostream>

class my_exception: public std::exception{
public:
    int value;
};

void f(my_exception& ex) {
    ex.value = 1;
    try {
        throw ex;
    } catch (my_exception& e) {
        e.value = 2;
        // Here's the re-throw
        throw;
    }
}

int main()
{
    my_exception ex;
    try {
        f(ex);
    } catch (my_exception& e) {
        std::cout << e.value;
    }
    return 0;
}