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.
Regular constructor call for an automatic stack variable (destroyed at the end of the function).
Another constructor call.
The assignment operator is called because v2 was already created (we called the constructor for it) and now we’re assigning one existing object to another.
The copy constructor is called here because Object v4 is still not created, so we create it as a copy of v1. The assignment is taken here to mean the same as if you did
Object v4(v1)Call the constructor for a heap object (destroyed explicitly with
delete).The copy constructor is first called to copy v1 to the parameter var. It is called again to create a copy of var as return value to the caller. var is destroyed as it’s popped off the stack when exiting the function. The return value is destroyed after at the expression func(v1).
The object pointed at by pv5 is manually destroyed.
The automatic variables v1, v2, v4 (all having copied the id of v1 from either assignment or copy construction) are popped off the stack and the destructor is called for each.