Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception object lifetime

I want to know how the exception object is created ? and why the handler function parameter can be a non-const reference?

For example:

class E{
    public:
    const  char * error;
    E(const char* arg):error(arg){
    cout << "Constructor of E(): ";}

    E(const E& m){
        cout << "Copy constructor E(E& m): " ;
       error=m.error;
    }
};



int main(){
try{
    throw E("Out of memory");

}
catch(E& e){cout << e.error;}

}

Output: Constructor of E(): Out of memory

so I have throw E("out of memory") and E("out of memory")is just a temporary object and no object has been created except E("out of memory") because no copy constructor has been invoked. so even though this E("out of memory") is just a temporary object, I have a handler that take a non-const reference.

Can you explain to me why this is possible?

like image 418
AlexDan Avatar asked Oct 21 '12 15:10

AlexDan


1 Answers

want to know how the exception object is created ?

When you do this:

throw E("Out of memory");

You create an object (of type E) locally. The processes of throwing copies this object to some private memory location not defined by the standard. Thus the object being thrown must be copyable.

Note: the compiler is allowed to optimize out the copy and create it directly in the private location. So the fact that it is not copied is because the compiler optimized away the copy (so it is not local anymore). Try making the copy constructor private and now it will fail to compile.

and why the handler function parameter can be a non-const reference ?

When you catch the object:

catch(E& e)

You are getting a reference to the object at the private location it was copied to. Its not a const (or temporary) value so you can have a normal reference to it.

like image 63
Martin York Avatar answered Oct 13 '22 20:10

Martin York