Sebastian Lenartowicz Sebastian Lenartowicz - 2 months ago 4
C++ Question

What constructor is called in this case?

Let's say I have an object

class A {
int bar();

A foo() {return A();}
int A::bar() {return 5;}

And then I do this:

int i = foo().bar();

What constructor is invoked for the temporary value created when


The code is:

A foo() {return A();}

When foo() is called , the sequence of effects is:

  1. Temporary created by A() using A's default constructor.
  2. Return value object of type A created using copy/move constructor, with step 1's temporary as argument (that is, move constructor if it exists, otherwise copy constructor).
  3. Temporary from step 1 is destructed.

However this is a copy elision context, so the compiler might combine all 3 steps into one, and create the return value object using A's default constructor.

What happens to the return value object depends on what the calling code does. There might be further copy elision. In the usage:

int i = foo().bar();

nothing else happens; bar() is called on the return value object, the value is assigned to i, and then the return value object is destroyed.