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++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01