Copy constructor required but not used?

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.

Please have a look at the following code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>

using namespace 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.
I see, so as soon as there is a 'potential' it is required?

Is there a way to force that it uses my copy constructor in this situation?
Topic archived. No new replies allowed.