Exception and Copy: C ++

Referring to http://en.wikipedia.org/wiki/Copy_elision

I run the code below:

#include <iostream> struct C { C() {} C(const C&) { std::cout << "Hello World!\n"; } }; void f() { C c; throw c; // copying the named object c into the exception object. } // It is unclear whether this copy may be elided. int main() { try { f(); } catch(C c) { // copying the exception object into the temporary in the exception declaration. } // It is also unclear whether this copy may be elided. } 

The output I received is:

 Gaurav@Gaurav-PC /cygdrive/d/Trial $ make clean rm -f Trial.exe Trial.o Gaurav@Gaurav-PC /cygdrive/d/Trial $ make g++ -Wall Trial.cpp -o Trial Gaurav@Gaurav-PC /cygdrive/d/Trial $ ./Trial Hello World! Hello World! 

I understand that the compiler could optimize the code with unnecessary copying, which it does not do here.

But what I want to ask is: how are two calls to the copy constructor executed?

catch(C c) - As we pass by value, therefore the copy constructor is called here.

But in throw c how is the copy constructor called? Can someone explain?

+8
c ++
source share
1 answer
 throw c; 

Creates a temporary object and creates this temporary object. Creating a temporary can be related to the copy / move constructor. And yes, this copy / move can be undone.


Literature:
C ++ 11 15.1 Throwing an exception

ยง3:

An expression expression initializes a temporary object called an exception object , the type of which is determined by removing any top-level cv qualifiers from the static type of the throw operand and setting the type .........

ยง5:

When the thrown object is an object of the class, the copy / move constructor and destructor must be available, even if the copy / move operation is completed (12.8).

+11
source share

All Articles