c++ - 正确使用析构函数

标签 c++ dynamic-memory-allocation

我刚开始使用 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 ,它表示您不应该执行任何 newdelete,除非是在仅拥有存储空间的类中。

关于c++ - 正确使用析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42910533/

相关文章:

c++ - 从字符串转换为 unsigned char* 会留下垃圾

c++ - 如何获取指向动态分配对象的指针的基地址

c++ - 如何从 int* 类型的堆分配数组中检索 int[num_elem] 类型的变量?

c - C 中的变量指针

c - 在c中的另一个函数中分配结构

android - 如何使用 'CMakeLists.txt' 中的 add_library 将整个文件(.cpp、.h 等)包含在目录中

c++ - 是否可以在 std::any 中存储引用?

c++ - 在 Fix8 C++ 库中运行 Linux 配置错误?

c++ - Qt 问题到全屏 Flash 应用程序

c - 在 C 中为队列的前面元素分配内存时出现段错误