Why copy constructor is not called

Here is a simple class header file and main program. In the main program, I thought that the copy constructor is called in exactly three situations: initialization (explicit copy), passing by value for function arguments and returning by value for functions. However, it seems that it is not called for one of them, I think that either (3) or (4), as indicated in the comments. For which numbers (1) - (4) is it called? Thanks.

Xh:

#include <iostream>

class X
{
public:
    X() {std::cout << "default constructor \n";}
    X(const X& x) { std::cout << "copy constructor \n";}
};

Main:

#include "X.h"

X returnX(X b)  // (1) pass by value - call copy constructor?
{
    X c = b;  // (2) explicit copy - call copy constructor?
    return b;  // (3) return by value - call copy constructor?
}

int main()
{
    X a; // calls default constructor

    std::cout << "calling returnX \n\n";
    X d = returnX(a);  // (4) explicit copy - call copy constructor?
    std::cout << "back in main \n";
}

Output:

default constructor
calling returnX

copy constructor
copy constructor
copy constructor 
back in main
+4
source share
2 answers

++ , , ( ) . , / , (.. , ).

, 12.8 [class.copy]:

  • return , , .
  • throw try - .
  • , .
  • catch , throw, .

, , . , , : - identity():

template <typename T>
T const& identity(T const& object) {
    return object;
}
...
X d = identity(returnX(a));

( , , T&& , , , return).

+7

4 . copy elision. , .

+6

All Articles