【发布时间】:2017-05-18 05:44:09
【问题描述】:
我是编程和学习课程的初学者。我正在关注 archived online course 并为 class Polygon 创建析构函数。
answer given 有~Polygon 没有删除PointArray points 的行,只包含减少numPolygons 的行。
我会假设~PointArray 以某种方式被激活以删除points。
为什么我们不必在
~Polygon中输入delete[] &points;?如果我的假设是正确的,PointArray 的析构函数何时以及如何生效?
在
~Polygon中添加delete[] &points;会如何影响程序?
以下简化代码在 Visual Studio Community 2015 下编译。
谢谢!
class Point {
private: int x, y;
public:
Point(int x = 0, int y = 0) {
this->x = x; // initializes (*this).x with x
this->y = y; // initializes (*this).y with x
}
// other member functions...
};
class PointArray {
int len;
Point *points;
public:
PointArray() {
len = 0;
points = new Point[0];
}
PointArray(const Point copyPoints[], const int size) {
points = new Point[size];
len = size;
for (int i = 0; i < size; ++i) points[i] = copyPoints[i];
}
PointArray(const PointArray &pv) {
len = pv.len;
points = new Point[len];
for (int i = 0; i < len; ++i) points[i] = pv.points[i];
}
~PointArray() {
delete[] points;
}
// other member functions...
};
class Polygon {
protected:
PointArray points;
static int numPolygons; // tracks # of Polygon instances/objects
public:
Polygon(const Point pointArr[], const int numPoints)
: points(pointArr, numPoints) { // initializes internal PointArray
++numPolygons; // +1 (initialized)
}
Polygon(const PointArray &pa)
: points(pa) { // initializes internal PointArray with arg
++numPolygons;
}
~Polygon() {
//delete[] &points;
--numPolygons;
}
};
int main() { return 0; }
【问题讨论】:
-
您似乎正在使用
points = new Point[size];进行未定义的行为 -
PointsArray应该有一个重载的operator=成员函数以符合rule of three。 -
@DanielA.White 你是什么意思?
-
@PaulRooney 谢谢!我还没有学习复制赋值运算符。
标签: c++ class destructor new-operator delete-operator