Japhet Ye
Japhet Ye

Reputation: 9

Passing objects in C++ understanding the basics

Hi I'm trying to understand the basics of passing objects in C++ and I understand that when passing an object to a function, the copy constructor of that object is called and if the function returns an object the move constructor is called to return to the main. I also understand if an object falls out of scope they are destroyed by the destructors. However there seems to be an extra destructor in my program.

The output:

Top of Program
Constructors here
Constructor
Constructor
End of Constructors
BoxSendReturn function
Copy Constructor
Inside BoxSendReturn
Move Constructor
Move Assignment
Destructor
Destructor
Destructor
End of Box Send Return
Destructor
Destructor

Here is the code:

enter code here
#include<iostream>
using namespace std;
class Box{
   private:
   public:
      Box(){ cout<<"Constructor"<<endl; }
      ~Box(){ cout<<"Destructor"<<endl; }
      Box (const Box &other) { cout<<"Copy Constructor"<<endl; }
      Box (Box &&other) { cout<<"Move Constructor"<<endl; }
      Box operator=(const Box &other){ cout<<"Copy Operator"<<endl; }
      Box operator=(Box &&other){ cout<<"Move Assignment"<<endl;}
};

Box BoxSendReturn(Box b){
    cout<<"Inside BoxSendReturn"<<endl;
    return b;
}

int main(){
   cout<<"Top of Program"<<endl;
   cout<<"Constructors here"<<endl;
   Box b1, b2;
   cout<<"End of Constructors"<<endl; 
   cout<<"BoxSendReturn function"<<endl;
   b1 = BoxSendReturn(b2);
   cout<<"End of Box Send Return"<<endl;
   return 0;
}

Upvotes: 0

Views: 67

Answers (1)

Slava
Slava

Reputation: 44258

Your code has Undefined Behaviour:

  Box operator=(const Box &other){ cout<<"Copy Operator"<<endl; }
  Box operator=(Box &&other){ cout<<"Move Assignment"<<endl;}

assignment operators by signature must return object by value, but they miss return statement. If you fix that the count of ctors and dtors will match: live code

Btw: assignment operators usually return reference. They do not have to but this way assignment operator has the same behavior as embedded types do (return lvalue etc) and there is no reason to make extra copy.

Upvotes: 7

Related Questions