我有以下问题: 在myClass中,我希望默认初始化一个指向yourClass的指针,并使用一个新的yourClass地址。 不幸的是,如果我想在任何时候删除指针,我会得到一个(核心转储)。
class myClass
{
protected:
yourClass * yc;
public:
myClass() { yc = new yourClass(); }
myClass(yourClass * tyc ) { delete yc; yc = tyc; }
~myClass() { delete yc; yc = NULL; }
void setMyClass (yourClass * tyc) { delete yc; yc = tyc; }
void print () { yc->print(); }
};
int main()
{
yourClass b (//parameter);
myClass * a = new myClass();
a->print();
a->setMyClass(&b)
a->print();
delete a;
return 0;
}
a的print()应该产生两种不同的打印,取决于//参数。
我认为你的等级是yc;而不是yourClass * yc,但我想知道是否可能。
修改 我按以下方式重新编写代码并且它可以工作。仍然看起来很复杂,聪明的指针看起来很有希望,我仍然没有应用“三个规则”。 这里的代码。谢谢大家。
class myClass
{
protected:
yourClass * yc;
bool dynamic;
public:
myClass() { dynamic = true; yc = new yourClass (); }
myClass (yourClass * tyc )
{
// dynamic init (like default)
if (tyc == NULL ) { dynamic = true; yc = new yourClass (); }
// static use of yc
else { dynamic = false; yc = tyc; }
}
// because only if dynamic is true, we need to erase
~blu () { if (dynamic) { delete yc; dynamic = false; } }
void setMyClass(yourClass* tyc)
{
// leaving unchanged if new-stuff is NULL or like old-stuff
if ( tyc == yc || tyc == NULL ) return;
else // treating dynamic and static differently
{
if (dynamic) // if flag is set, must be deleted
{
delete yc; yc = tyc; dynamic = false;
}
else // must not be deleted, dynamic is still false
{
yc = tyc;
}
}
}
void print () { yc->print(); }
};
答案 0 :(得分:7)
那是因为你试图删除太多:
delete yc;
)delete a;
将尝试删除指向b的指针,b是堆栈中的对象;发生什么取决于你的操作系统(我期待一个例外/核心转储/无论如何)a->setMyClass(NULL)
我建议:
答案 1 :(得分:1)
你违反了三条规则。
这也是灾难的秘诀:
myClass(yourClass * tyc ) { delete yc; yc = tyc; }
如果tyc==yc
会怎样?对。不漂亮:))
myClass(yourClass * tyc ) { if (yc!=tyc) { delete yc; yc = tyc; } }