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?