1

I'm working through chapter 18 of Stroustrup's Principles and Practice and am stuck on one part related to copy constructors.

I have a copy constructor defined as:

X(const X& x) {
    out("X(X&)");
    val = x.val;
}

X is a struct. val is just an int value of X. 'out' is:

void out(const string& s) {
    cerr << this << "->" << s << ": " << val << "\n";
}

I also have the following 2 functions defined:

X copy(X a) {
    return a;
}

and

X copy2(X a) {
    X aa = a;
    return aa;
}

In main I have:

X loc(4);
X loc2 = loc;
loc2 = copy(loc);
loc2 = copy2(loc);

When I just call copy, the copy constructor is called twice: once for copy's parameter scope and once for the return call. This makes sense to me.

However, when I call copy2, the copy constructor is still just called twice: once for the function argument and once for 'X aa = a.' Why isn't it also called for the return?

MattHusz
  • 452
  • 4
  • 15

2 Answers2

2

There's no guarantee that copy constructors will be called in C++. In the case of return, it's likely to be replaced by a move or completely elided.

See also: What are copy elision and return value optimization?

Community
  • 1
  • 1
Tatsuyuki Ishi
  • 3,883
  • 3
  • 29
  • 41
0

Since you are returning a local variable, move semantics apply.

Optimizations make copying, moving and returning even more elaborate, see Tatuyuki Ishi's answer.

Here are some good examples for move semantics for return statements.

Community
  • 1
  • 1
DaveFar
  • 7,078
  • 4
  • 50
  • 90