[英]C++ Memory Leak Using STL Containers
The following code is giving me a memory leak (using Visual Studio): 以下代码给了我内存泄漏(使用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;
}
I presume this is because the STL vector container is using memory on the heap when the Subject
class is instantiated. 我认为这是因为实例化
Subject
类时,STL矢量容器正在堆上使用内存。 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). (我曾尝试删除
Subject
析构函数中的容器,但这似乎不起作用)。
The vector
is destroyed when the program exits, you don't need to ensure it. 程序退出时,
vector
被销毁,您无需确保它。 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": 您确实需要确保在销毁之后调用
_CrtDumpMemoryLeaks
,如果您不希望它报告分配的内存为“泄漏”:
int main()
{
{ Subject subject; }
_CrtDumpMemoryLeaks();
return 1;
}
std::vector<Listener*> listeners;
will not free the members of Listeners. 不会释放侦听器的成员。 You'd have to delete each of the listeners that are inside the vector, using something like:
您必须使用以下方法删除向量中的每个侦听器:
for (int i = 0; i < listeners.size(); i++) delete listeners[i]
Personally, I avoid such issues by using smart pointers: 就个人而言,我通过使用智能指针来避免此类问题:
std::vector<std::unique_ptr<Listener>> listeners
_CrtDumpMemoryLeaks detects leaks by counting news and making sure they all match. _CrtDumpMemoryLeaks通过计数新闻并确保它们都匹配来检测泄漏。 Because subject never goes out of scope, I'm guessing it is counted as an outstanding reference.
因为主题永远不会超出范围,所以我认为它被认为是出色的参考。 Try
int main(void) {{Subject subject;}_CrtDumpMemoryLeaks(); return 1}
尝试
int main(void) {{Subject subject;}_CrtDumpMemoryLeaks(); return 1}
int main(void) {{Subject subject;}_CrtDumpMemoryLeaks(); return 1}
Make sure that the Listener
destructor destroys everything it needs to. 确保
Listener
析构函数销毁它所需的所有内容。 All the STL container does is invoke the destructor of the object it is holding. STL容器所做的所有事情就是调用其持有的对象的析构函数。 It is still your responsibility to handle memory in the class itself.
在类本身中处理内存仍然是您的责任。
To be more specific, anything declared with a new
or malloc
in the class must be freed by the destructor. 更具体地说,析构函数必须释放在类中用
new
或malloc
声明的任何内容。 The STL container won't know how to delete that. STL容器不知道如何删除它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.