我有以下问题: 在 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() 应该会产生两个不同的打印,具体取决于 //parameters。
我考虑过你的类 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(); }
};