使用 STL 容器的 C++ 内存泄漏

2021-12-31 00:00:00 memory-leaks c++ stl

以下代码导致内存泄漏(使用 Visual Studio):

The following code is giving me a memory leak (using Visual Studio):

#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#include <vector>
#include <memory>

struct Listener {};

struct Subject
{
    std::vector<Listener*> listeners;
};

int main(void)
{
    Subject subject;
    _CrtDumpMemoryLeaks();
    return 1;
}

我认为这是因为在实例化 Subject 类时 STL 向量容器正在使用堆上的内存.如何确保程序退出时vector容器被销毁?(我已经尝试删除 Subject 析构函数中的容器,但这似乎不起作用).

I presume this is because the STL vector container is using memory on the heap when the Subject class is instantiated. How do I ensure that the vector container is destroyed when the program exits? (I've tried deleting the container in the Subject destructor, but that doesn't seem to work).

推荐答案

vector 是在程序退出时被销毁,你不需要确保它.如果您不想将分配的内存报告为泄漏",您确实需要确保在销毁后调用 _CrtDumpMemoryLeaks:

The vector is destroyed when the program exits, you don't need to ensure it. You do need to ensure that _CrtDumpMemoryLeaks is called after that destruction if you don't want it to report the allocated memory as "leaked":

int main()
{
    { Subject subject; }
    _CrtDumpMemoryLeaks();
    return 1;
}

相关文章