Throw an exception by value or reference

From this answer qaru.site/questions/1004509 / ... :

An expression expression without operands returns the current exception handling. The exception is renewed with the existing temporary; no new temporary exception object is created. - ISO / IEC 14882: 2011 Clause 15.1 par. 8

So why am I getting this result from this code?

the code:

#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;
}

Actual result:

1

I thought it should be 2 depending on the standard quota. What am I missing?

+4
source share
2 answers

This is a beacuse throw (regular version) to make a copy :

-, copy- ( rvalue, / ),...

, e.value=2; .

SO , , .

+7

( ), . , , :

#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 the re-throw
        throw;
    }
}

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

All Articles