nik*_*te 3 c++ copy object delete-operator
如何从浅复制对象与原始对象中删除双(删除)错误.
一个简单的例子:
class INT
{
int *p; //dynamic.
//define here fancy constructors etc.
set(int i){ p=new int; p=i;}
~INT();
}
INT::~INT()
{
if(p) delete p;
}
void somefunction(INT a)
{
//done some stuff ,e.g. call some display function
}
//note here, that a destructor will be called, and a.p will vanish.
int main(void)
{
INT a; a.set(2);
somefunction(a);//shallow copy
}
//CRASH BOOM BOOM!
Run Code Online (Sandbox Code Playgroud)
我想要一个通用的解决方案,因为传递对象是一件微不足道的事情,而像这样天真的东西,导致一个可怕/可怕的错误只是'真棒'.
我怀疑有很多方法(其中一些甚至我都能想到),但我很好奇是否有任何通用(适用于几乎所有地方)解决这个问题的方法?
| 归档时间: |
|
| 查看次数: |
1229 次 |
| 最近记录: |