Copy constructor invoked question

Dear C++ Community

I encountered a question, if the following program fragment was run the copy constructor for the class X would be invoked three times.

1
2
3
4
5
6
7
8
9
10
11
12
// the following function declarations are assumed
// X(int) // a one-argument constructor
// X getX(int)
// void printX1(const X&)
// void printX2(X)

X x(1);
X y(x);
X z = x;
X x2 = getX(4);
printX1(x);
printX2(y);


-------------------------------------------------------------------------------
My attempt:
===========
I think the three times the copy constructor might be invoked:

1) X x2 = getX(4); [We are taking our own copy of the x variable from a class]

2) X x(1); [A one-argument constructor is being called. We still have the a value of our own in a variable]

3) X y(x); [We are keeping the value 'x' in our own variable, for our own use.]

Any help is much appreciated.
- The copy constructor would not be invoked on line 7.
By definition, a copy constructor for a class X is a one-argument constructor that takes a reference to (const) X. (roughly).

The one-argument constructor taking int is called a converting constructor, because it allows users to convert an int into an X.

- The copy constructor would be invoked on line 8 and line 9.

- The copy constructor wouldn't be invoked on line 10, but that's not really a beginner's question:

The initializer expression is a prvalue with type cv X, so copy elision occurs. No temporary object is materialized and copied. Instead, the variable x2 is treated as the result object of the initializer expression and is constructed in-place.
https://en.cppreference.com/w/cpp/language/copy_elision

This is the C++17 behavior. In C++14, compilers are allowed but not required to omit the invocation of the copy constructor even if it has side effects. Before C++14, the as-if rule is applied here, and copy construction must occur, but only if that copy constructor has observable side-effects.

- The copy constructor would invoked on line 12: the argument y is copied into the parameter of print2().
Last edited on
Topic archived. No new replies allowed.