我试图理解复制构造函数的概念.我用这个例子:
#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;
}
Run Code Online (Sandbox Code Playgroud)
问题是,为什么我在这里得到运行时错误?如果我定义了一个复制构造函数,它为新的ptr分配内存,并将line1分配给line2,那是不是意味着这两个是单独的对象?通过破坏line1,我显然也搞乱了line2,或者我使用析构函数调用错了?
您在此语句中调用了析构函数
line1.~Line();
Run Code Online (Sandbox Code Playgroud)
删除了分配的内存 ptr
Line::~Line()
{
delete ptr;
};
Run Code Online (Sandbox Code Playgroud)
但是该对象line1是活动的,因为它具有自动存储持续时间.因此,在退出main之后,将再次调用该对象的析构函数,因此它将尝试删除ptr已明确删除的内存所指向的内存.
| 归档时间: |
|
| 查看次数: |
79 次 |
| 最近记录: |