わお....
MyObject::MyObject( const MyObject& oCopy)
{
*this = oCopy;//is this deep or shallow?
}
どちらでもない。代入演算子の呼び出しです。
オブジェクトの構築が完了していないため、これはおそらく賢明ではありません (完全に有効ですが)。ただし、代入演算子をコピー コンストラクターの観点から定義する方がより伝統的です (copy and swap idium を参照)。
const MyObject& MyObject::operator=(const MyObject& oRhs)
{
if( this != oRhs ){
members = oRhs.members;
.....//there is a lot of members
}
return *this;
}
基本的には問題ありませんが、通常、代入の結果は con ではありません。
ただし、この方法で行う場合は、例外を安全にするために処理を少し分割する必要があります。次のようになります。
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;
}
もちろん、copy and swap 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;
}