Question

In c++ the following code.

#include <iostream>
using namespace std;

class Object {

public:
   Object(int id){
     cout << "Construct(" << id << ")" << endl;
     m_id = id;
   }

   Object(const Object& obj){
      cout << "Copy-construct(" << obj.m_id << ")" << endl;
      m_id = obj.m_id;
   }

   Object& operator=(const Object& obj){
      cout << m_id << " = " << obj.m_id << endl;
      m_id = obj.m_id;
      return *this;
   }

   ~Object(){
       cout << "Destruct(" << m_id << ")" << endl;
   }
private:
   int m_id;

};

int main(){
   Object v1(1);
   cout << "( a )" << endl;
   Object v2(2);
   v2 = v1;
}

and associated output

Construct(1)
( a )
Construct(2)
2 = 1

Why after the = operator, destructor isn't called. the obj in operator = should exit the scope and should invoke a destructor upon itself? Isn't it so?

Was it helpful?

Solution

No. 'obj' wasn't created in the scope so it isn't destroyed in the scope. It's a parameter, and it's a reference. The actual object is elsewhere.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top