when throw is used to throw object and catch gets it by reference (&) this supposes to create the object directly in the catch, i made 2 codes which somehow describe a strange behavior occurring in my visual studio express 2012, 1st code :
the difference between 2 codes is in the 1st constructor. the 1st code resulted in : throw creates an object, then copies it to catch, then throw deletes the original object. the 2nd code behaves normally. what does the problem seem ?
The copy ctor should take a const reference anyway.
Likewise, your catch should be catching a const reference.
But what is happening is that the compiler is making an optimization on the second code that it fails to make on the first.
First code: you create an A1 (belongs to local stack) and throw it. Compiler creates a copy of A1 as A2 -- not on the local stack. A1 is then destructed along with the stack frame from yes(). A2 is caught.
Second code: you create an A which the compiler knows has absolutely no side effects -- it is created to be thrown -- it is created somewhere other than the local stack -- no copy ctor is needed. yes()'s local stack frame is destroyed. A is caught.