Validity Period of Exclusion Object

I want to know how an exception object is created? and why the parameter of the handler function can be a non-constant 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;} } 

Exit: Constructor E (): from memory

therefore, I throw E("out of memory") and E("out of memory") is just a temporary object, and the object was not created except for E("out of memory") because the copy constructor was not called. so even if this E("out of memory") is just a temporary object, I have a handler that accepts a non-constant reference.

Can you explain to me why this is possible?

+8
c ++ object exception lifetime
source share
1 answer

Want to know how an exception object is created?

When you do this:

 throw E("Out of memory"); 

You create an object (type E) locally. Throwing processes copy this object to some private storage that is not defined by the standard. Thus, the created object must be copied.

Note: the compiler is allowed to optimize the copy and create it directly in a private place. Therefore, the fact that it is not copied is that the compiler optimized the copy (so that it is no longer local). Try to make the copy constructor private, and now it will not compile.

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

When you catch an object:

 catch(E& e) 

You get a link to the object in the private place to which it was copied. This is not a constant (or temporary) value, so you can have a normal reference to it.

+10
source share

All Articles