哇....
MyObject::MyObject( const MyObject& oCopy)
{
*this = oCopy;//is this deep or shallow?
}
两者都不是。这是对赋值运算符的调用。
由于您尚未完成对象的构造,因此这可能是不明智的(尽管完全有效)。但是,根据复制构造函数定义赋值运算符更为传统(请参阅复制和交换 idium)。
const MyObject& MyObject::operator=(const MyObject& oRhs)
{
if( this != oRhs ){
members = oRhs.members;
.....//there is a lot of members
}
return *this;
}
基本上没问题,虽然通常分配的结果不是续的。
但是如果你这样做,你需要稍微划分你的处理以使其异常安全。它应该看起来更像这样:
const MyObject& MyObject::operator=(const MyObject& oRhs)
{
if( this == oRhs )
{
return *this;
}
// Stage 1:
// Copy all members of oRhs that can throw during copy into temporaries.
// That way if they do throw you have not destroyed this obbject.
// Stage 2:
// Copy anything that can **not** throw from oRhs into this object
// Use swap on the temporaries to copy them into the object in an exception sage mannor.
// Stage 3:
// Free any resources.
return *this;
}
当然,使用复制和交换 idum 有一种更简单的方法:
MyObject& MyObject::operator=(MyObject oRhs) // use pass by value to get copy
{
this.swap(oRhs);
return *this;
}
void MyObject::swap(MyObject& oRhs) throws()
{
// Call swap on each member.
return *this;
}
如果在析构函数中没有什么可做的,请不要声明它(除非它需要是虚拟的)。
MyObject::~MyObject(){
//there is nothing here
}
在这里,您声明了一个指针(不是对象),因此不调用构造函数(因为指针没有构造函数)。
const MyObject * mpoOriginal;//this gets initialized in the constructor
在这里,您正在调用 new 来创建对象。
你确定你要这么做吗?必须销毁动态分配的对象;表面上是通过删除,但更常见的是在 C++ 中,您将指针包装在智能指针中,以确保所有者正确并自动销毁对象。
int main()
{ //^^^^ Note main() has a lower case m
mpoOriginal = new MyObject();
return DoSomething();
}
但是因为您可能不想要动态对象。您想要的是在超出范围时被销毁的自动对象。此外,您可能不应该使用全局变量(将其作为参数传递,否则您的代码正在使用与全局状态相关的副作用)。
int main()
{
const MyObject mpoOriginal;
return DoSomething(mpoOriginal);
}
您不需要调用 new 来进行复制,只需创建一个对象(传递您要复制的对象)。
bool DoSomething(MyObject const& data)
{
MyObject poCopied (data); //the copy
//lots of stuff going on
// No need to delete.
// delete poCopied;//this causes the crash - can't step into using GDB
// When it goes out of scope it is auto destroyed (as it is automatic).
return true;
}