c++ - Temporary object not getting created when exception is caught by reference? -
class error1 { public: int errorcode; error1(int x):errorcode(x){ cout<<"ctor error1"<<endl; } //error1(error1& obj ){ // errorcode = obj.errorcode; // cout<<"copyctor error1"<<endl; //} ~error1(){cout<<"dtor error1"<<endl; } }; void fun() { cout<<"inside fun"<<endl; throw(error1(5)); } int main() { try{ fun(); } catch(error1& eobj) { cout<<"error1 type occured code:"<<eobj.errorcode<<endl; } cin.get(); }
output:
inside fun ctor error1 dtor error1 error1 type occured code:5 dtor error1
this output indicates error1 object copy constructed catch handler. since copy constructor not defined error1 object default copy constructor used.
when uncomment commented section defining copy constructor the following output.
inside fun ctor error1 error1 type occured code:5 dtor error1
why 1 dtor getting called? if exception caught reference believe temporary still created.
what compiler using?
when introduce (i.e. uncomment) version of copy constructor error1& obj
argument, code supposed become invalid. throw
supposed able create copy of argument, while version of copy constructor disables copying of temporaries. code ill-formed. if compiler accepts it, because illegally allows binding non-const references temporaries (i suspect msvc++ compiler extensions enabled).
the original experiment works supposed/allowed to. argument of throw
copied internal temporary later used initialize catch
parameters. although compilers allowed use original temporary directly, extending lifetime accordingly.
Comments
Post a Comment