我刚开始使用 C++,现在我有一个非常基本的问题。
我写了 2 个类:
坐标:
#include <stdio.h>
class Coordinate {
private:
int x;
int y;
public:
Coordinate(int a, int b) {
x = a;
y = b;
};
void printTest() {
printf("%d %d\n", x, y);
};
};
测试:
class Test {
private:
int q;
Coordinate *point;
public:
Test(int a, int b, int c) {
q = a;
point = new Coordinate(b, c);
};
virtual ~Test() {
delete point;
}
};
主要功能:
int main() {
Test *test = new Test(1, 2, 3);
// ...
delete test;
return 0;
}
在我的 main
中,我使用了 Test
类的对象。我编写了自己的 Test
析构函数,但我不确定这个析构函数是否按预期工作。它是否完全释放了 test
的内存?还是我必须对 q
属性做些什么才能释放它?
最佳答案
就目前而言,您所做的是正确的。 Valgrind 报告
==28151== HEAP SUMMARY:
==28151== in use at exit: 0 bytes in 0 blocks
==28151== total heap usage: 3 allocs, 3 frees, 72,736 bytes allocated
==28151==
==28151== All heap blocks were freed -- no leaks are possible
您缺少的是编译器为您提供了默认的复制构造函数和赋值运算符。这些将复制指针,而不是创建一个新的指向值,所以任何时候你复制一个Test
对象你就会有两个其析构函数都将尝试删除相同存储的对象。这是双重免费,它会毁了你的一天。
为避免这种情况,C++ 程序员使用 Rule of Three 或 五法则 在编写类(class)时,或者 - 甚至更好 - Rule of Zero ,它表示您不应该执行任何 new
或 delete
,除非是在仅拥有存储空间的类中。
关于c++ - 正确使用析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42910533/