0

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
K.Karamazen
  • 176
  • 1
  • 8
  • 2
    Since C++11, the compiler is optionally allowed to eliminate the copy when initializing an object from a prvalue of the same type. See the linked question for a more general introduction to copy elision. Since C++17 this is mandatory in certain situations. – Sam Varshavchik Oct 15 '20 at 14:08
  • 1
    @SamVarshavchik Oh really, I thought compilers were allowed to do that since 98? – cigien Oct 15 '20 at 14:09

0 Answers0