#include <iostream>
using namespace std;
class X {
public:
X() {
cout<<"Cons"<<endl;
}
X(const X& x){
cout<<"Copy"<<endl;
}
void operator=(const X& x){
cout<<"Assignment called";
}
};
X& fun() {
X s;
return s;
}
int main(){
X s = fun();
return 0;
}
This code calls the copy constructor also. Why does this work? I recall that the first time I ran this program, it seg faulted. But after a while, it started calling this copy cons. and now works!! Wierd.
But if I replace, fun() as follows:
X fun() {
X s;
return s;
}
Then copy cons. is not called. I thought that the copy cons. would be called in this case. But as pointed out by @flyfishr64, RVO is coming into play here. But it still does not explain the case where I am returning a reference. I think it should always segfault.
Any explanations?