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
- 静态初始化顺序失败 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 从python回调到c++的选项 2022-11-16
- Stroustrup 的 Simple_window.h 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 近似搜索的工作原理 2021-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01