In solving a assignment in Bruce Eckel's C++ book I created the following code. It does what it is supposed to do. But there is one thing I don't understand.
#include <iostream>
usingnamespace std;
#define t(STR) cout << STR << endl;
/*19*/
class One {
public:
int x;
public:
One(int i=12) : x(i) { t("One is created"); }
One(const One& t ) { x = t.x; t("One is copied"); }
~One() { t("One is destroyed"); }
};
One f() {
One x;
x.x = 16;
return x;
}
int main() {
t("begin main()");
One d = f(); //why does this not trigger const One& t copy-constructor
t(d.x);
t("end main()");
}
begin main()
One is created
16
end main()
One is destroyed
If I remove the word const, in the copy constructor, it's generating an error for One d = f();. I wonder, why? It appears it's not using that copy-constructor at all.. if it does, why is it totally ignoring the code I wrote for this copy-constructor?
Two potential copies happen in your code: one in line 20, where the local object x is copied to the return value and another in line 25 where you're copy-initializing d with the temporary object returned by f(). For this reason a copy constructor is required.
The reason it's not actually called is that the C++ standard allows the compiler to elide both copies. When the compiler makes use of this, x in f() is constructed directly into d and the copy constructor is never called.