I can't figure out why the copy-constructor is not called when I try to return a local variable defined within a function. See the following simplified example:
#include <iostream>
using namespace std;
class X {
public:
X() { cout << "Default Constructor" << endl; }
X(const X&) { cout << "Copy Constructor" << endl; }
};
X f(X x) { return x; }
X g() {
X y;
return y;
}
int main() {
cout << "First create an object" << endl;
X a;
cout << "Call f()" << endl;
f(a);
cout << "Call g()" << endl;
g();
}
The output of the complied program is as follows
First create an object
Default Constructor
Call f()
Copy Constructor
Copy Constructor
Call g()
Default Constructor
I understand what's going on when calling f()
, but have no idea why return y
inside the call of g()
does not trigger the copy-constructor.