【发布时间】:2014-01-30 14:18:33
【问题描述】:
这里是代码
#include <iostream>
#include <stdio.h>
using namespace std;
class Point {
private:
int x;
int y;
public:
Point(int x, int y) : x(x), y(y) {}
~Point() {
printf("Point destroyed: (%d, %d)\n", x, y);
}
};
class Square {
private:
Point upperleft;
Point lowerright;
public:
Square(int x1, int y1, int x2, int y2) : upperleft(x1, y1), lowerright(x2, y2) {}
Square(Point p1, Point p2) : upperleft(p1), lowerright(p2) {}
~Square() {
printf("Square destroyed.\n");
}
};
int main(int argc, char const* argv[])
{
Point p1(1, 2);
Point p2(3, 4);
Square s1(p1, p2);
return 0;
}
编译(g++ x.cpp)运行后,得到如下结果:
Point destroyed: (1, 2)
Point destroyed: (3, 4)
Square destroyed.
Point destroyed: (3, 4)
Point destroyed: (1, 2)
Point destroyed: (3, 4)
Point destroyed: (1, 2)
我希望每个点被摧毁两次,但它们被摧毁了三次。为什么?
【问题讨论】:
-
什么编译器和什么选项?
-
p1 和 p2 将被销毁,将它们传递给
Square构造函数时生成的副本以及从这些副本构造数据成员时生成的第二对副本也会被销毁。 -
@JohnZwinck 请查看编辑。
-
如何通过它们而不构建新的?通过引用?
-