私はこのコピーコンストラクタの問題を理解しようとしています。私が持っている質問は、プログラムが終了した後にデストラクタに関係します。変数char * titleは破壊されていないようですが、これは間違っていると思います。コピーコンストラクタの質問
オブジェクトxがx2に等しいときに代入演算子が呼び出されないのはなぜですか?私はコードブロックでg ++を使用しています。
#include <iostream>
using namespace std;
class myClass
{
private:
int x;
int *p;
char* title;
public:
myClass(int tx, int* temp, char* newtitle)
{
x = tx;
cout << "int constructor called with value x = " << x << endl;
p = new int;
p = temp;
title = new char [strlen(newtitle)+1];
strcpy(title, newtitle);
}
myClass(const myClass& mc)
{
cout << "copy constructor called with value = " << mc.x << endl;
x = mc.x;
p = new int;
*p = *mc.p;
title = new char [strlen(mc.title)+1];
strcpy(title, mc.title);
}
myClass & operator = (const myClass & that)
{
cout << "assignment called" << endl;
if(this != &that)
{
x = that.x;
}
return *this;
}
~myClass()
{
if (p)
{
cout<<"deleting p"<<endl;
delete p;
}
else if(title)
{
cout<<"deleting title"<<endl;
delete[] title;
}
}
};
int main()
{
int pointee = 10;
int* p = &pointee;
myClass x(3,p,"hello");
//myClass y = myClass(3,p);
myClass x2 = x;
return 0;
}
フォーマットが修正されました。 –
デストラクタで "else if(title)"の代わりに "if(title)"が必要な場合があります – DReJ
好奇心をそそる人:OPを含む人が多すぎるため、時間は、お互いの変更を上書きします。 – sbi