C++ Memory Leak Using STL Containers(使用 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;
}
我认为这是因为在实例化 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;
}
这篇关于使用 STL 容器的 C++ 内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 STL 容器的 C++ 内存泄漏
基础教程推荐
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 从 std::cin 读取密码 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01