destructor and copy-constructor calling..(why does it get called at these times)

Posted by sil3nt on Stack Overflow See other posts from Stack Overflow or by sil3nt
Published on 2010-06-06T06:58:14Z Indexed on 2010/06/06 7:02 UTC
Read the original article Hit count: 239

Filed under:
|
|
|
|

Hello there, I have 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;

};

Object func(Object var) { return var; }

int main(){
   Object v1(1);
   cout << "( a )" << endl;
   Object v2(2);
   v2 = v1;
   cout << "( b )" << endl;
   Object v4 = v1;
   Object *pv5;
   pv5 = &v1;
   pv5 = new Object(5);
   cout << "( c )" << endl;
   func(v1);
   cout << "( d )" << endl;
   delete pv5;
}

which outputs

Construct(1)
( a )
Construct(2)
2 = 1
( b )
Copy-construct(1)
Construct(5)
( c )
Copy-construct(1)
Copy-construct(1)
Destruct(1)
Destruct(1)
( d )
Destruct(5)
Destruct(1)
Destruct(1)
Destruct(1)

I have some issues with this, firstly why does Object v4 = v1; call the copy constructor and produce Copy-construct(1) after the printing of ( b ).

Also after the printing of ( c ) the copy-constructor is again called twice?, Im not certain of how this function works to produce that Object func(Object var) { return var; }

and just after that Destruct(1) gets called twice before ( d ) is printed.

sorry for the long question, I'm confused with the above.

© Stack Overflow or respective owner

Related posts about c++

Related posts about gcc