class TestObj
{
public:
TestObj()
{
cout << "TestObj()\n";
}
~TestObj()
{
cout << "~TestObj()执行\n";
}
void showMsg()
{
cout << "showMsg()\n";
}
};
class ManageObj
{
public:
ManageObj(TestObj *pObj) :m_pObj(pObj)
{
}
~ManageObj()
{
if (m_pObj)
{
delete m_pObj;
m_pObj = NULL;
}
}
TestObj*GetObj()
{
return m_pObj;
}
protected:
private:
TestObj *m_pObj;
};
void main()
{
{
ManageObj MO(new TestObj);
MO.GetObj()->showMsg();
}
system("pause");
}
结果: 接着改变main()
void main()
{
{
ManageObj MO(new TestObj);
MO.GetObj()->showMsg();
ManageObj Mb(MO);
Mb.GetObj()->showMsg();
}
system("pause");
}
结果: 所以一般RALL对象在复制自己时,应该一并复制它所管理的对象。我个人推介RALL对象就不要自己复制自己了。所以增加如下类:
class UnCopyAble
{
protected:
UnCopyAble() = default;
~UnCopyAble() = default;
private:
UnCopyAble(const UnCopyAble&);
UnCopyAble&operator=(UnCopyAble &o);
};
class ManageObj:private UnCopyAble
{
...
}
结果:直接在编译期间就扼杀了。
|