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++ 内存泄漏


基础教程推荐
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 这个宏可以转换成函数吗? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 常量变量在标题中不起作用 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30