我试图理解复制构造函数的概念。我用这个例子:
#include <iostream>
using namespace std;
class Line
{
public:
int GetLength();
Line(int len);
Line(const Line &obj);
~Line();
private:
int *ptr;
};
Line::Line(int len)
{
ptr = new int;
*ptr = len;
};
Line::Line(const Line &obj)
{
cout << "Copying... " << endl;
ptr = new int;
*ptr = *obj.ptr;
};
Line::~Line()
{
delete ptr;
};
int Line::GetLength()
{
return *ptr;
}
int main()
{
Line line1 = Line(4);
cout << line1.GetLength() << endl;
Line line2 = line1;
line1.~Line();
cout << line2.GetLength() << endl;
return 0;
}
问题是,为什么在这里会出现运行时错误?如果我定义了一个复制构造函数,该复制构造函数为新的ptr分配了内存,并将line1分配给line2,那不是意味着这两个对象是单独的对象吗?通过销毁第1行,我显然也弄乱了第2行,还是我使用析构函数调用错了?
您在此语句中调用了析构函数
line1.~Line();
这删除了分配给的内存 ptr
Line::~Line()
{
delete ptr;
};
但是,该对象line1
是活动的,因为它具有自动存储时间。因此,在退出main之后,该对象的析构函数将再次被调用,结果它将尝试删除ptr
已经明确删除的那个对象所指向的内存。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句