【发布时间】:2016-02-27 10:00:24
【问题描述】:
我正在尝试理解复制构造函数的概念。我用了这个例子:
#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,这是否意味着这两个是单独的对象?通过破坏line1,我显然也搞砸了line2,还是我使用的析构函数调用错误?
【问题讨论】:
-
实现赋值运算符也是一个好习惯。但是在您的情况下,问题是显式的析构函数调用,您的指针将被删除两次,这会导致运行时错误。
-
你为什么要这么做
line1.~Line();?谁让你这么做的? -
这只是为了练习,我尝试这个看看当我破坏 line1 时 line2 对象会发生什么。我来自 C# 世界:)
-
@omegasbk 但随后它被破坏了两次
-
当我们超出范围时?
标签: c++