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(); }
};
本文探讨了在C++中使用默认构造函数初始化指针并动态分配对象的方法,包括对象复制、指针赋值和资源管理。
1525

被折叠的 条评论
为什么被折叠?



