我有以下代码
#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;
}
哪个输出
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)
我对此有一些问题,首先为什么要Object v4 = v1;
调用复制构造函数并Copy-construct(1)
在打印( b )
.
同样在复制构造函数的打印( c )
再次被调用两次之后?,我不确定这个函数是如何产生的
Object func(Object var) { return var; }
并且在 打印Destruct(1)
之前被调用两次。( d )
抱歉,这个问题很长,我对上述内容感到困惑。