使用STL容器的C ++内存泄漏 [英] C++ Memory Leak Using STL Containers

查看:176
本文介绍了使用STL容器的C ++内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码给我一个内存泄漏(使用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;
}

我认为这是因为STL向量容器在堆上使用内存 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).

推荐答案

程序退出时,向量 被销毁,您不需要确保它。您需要确保 _CrtDumpMemoryLeaks 在销毁后被调用,如果您不希望将分配的内存报告为leaked:

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;
}

这篇关于使用STL容器的C ++内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆