I have the following superficial example where I couldn't see why the copy constructor is only called once when I expected it to be called 4 times. I suspected Move Constructor is coming to play, but I couldn't prove it to myself that easily. So I decided to ask here. Sometimes very simple things are difficult for one person to see, but another sees it immediately.
# include <string>
# include <iostream>
class Obj {
public:
int var1;
Obj(){
std::cout<<"In Obj()"<<"\n";
var1 =2;
};
Obj(const Obj & org){
std::cout<<"In Obj(const Obj & org)"<<"\n";
var1=org.var1+1;
};
// all the same with move constructor
// Obj(Obj && org){
// std::cout<<"In Obj( Obj && org)"<<"\n";
// var1=org.var1+1;
// };
};
int main(){
{
/*const*/ Obj Obj_instance1; //const doesn't change anything
Obj Obj_instance2;
std::cout<<"assignment:"<<"\n";
Obj_instance2=Obj(Obj(Obj(Obj(Obj_instance1)))) ;
// in fact expected: 6, but got 3
std::cout<<"Obj_instance2.var1:"<<Obj_instance2.var1<<"\n";
//std::cout<<".var1:"<<Obj(Obj(Obj(Obj(Obj_instance1)))).var1<<"\n";
}
}
The result is:
In Obj()
In Obj()
assignment:
In Obj(const Obj & org)
Obj_instance2.var1:3