When I run the above program, the copy constructor is not called when the temporary variable from y() is passed by value to func(). I thought the whole point of passing by value is that a new object is made that is initialised with the value being passed. Does that only apply when the function argument is a global or static object?Code:#include <iostream> using namespace std; struct X { int i; X(int j = 0): i(j){cout << "constructor\n";} X(const X& x): i(x.i){cout << "copy constructor\n";} ~X(){cout << "destructor\n";} X& operator=(const X& x); }; X& X::operator=(const X& x) { cout << "assignment operator\n"; if (this != &x) i = x.i; return *this; } X y(int i) { cout << "in y()\n"; return X(i);//<-----------------This } //const X& func(const X& x) const X& func(X x)//<------------ends up here { cout << "in func()\n"; return x; } int main() { func(y(99)); return 0; }
Can anyone enlighten me as to why that should be the case?
Thanks.