<分区>
Visual Studio 2012 告诉我以下程序存在内存泄漏。这是正确的吗?如果是这样,我如何在使用(例如)静态 vector 时避免内存泄漏?
#include <crtdbg.h>
#include <vector>
struct A {
static std::vector<int> a;
};
std::vector<int> A::a;
int main()
{
_CrtDumpMemoryLeaks();
return 0;
}
<分区>
Visual Studio 2012 告诉我以下程序存在内存泄漏。这是正确的吗?如果是这样,我如何在使用(例如)静态 vector 时避免内存泄漏?
#include <crtdbg.h>
#include <vector>
struct A {
static std::vector<int> a;
};
std::vector<int> A::a;
int main()
{
_CrtDumpMemoryLeaks();
return 0;
}
最佳答案
您在静态变量的作用域完成之前调用函数。因此,您期望变量已被销毁是错误的。
在调用该函数之前,您需要等到作用域结束。当然这很难做到,但运行时可以帮助您,如 documentation 中所述。 :
The function can be called automatically at program termination by turning on the _CRTDBG_LEAK_CHECK_DF bit field of the _crtDbgFlag flag using the _CrtSetDbgFlag function.
关于静态变量导致的 C++ 内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19386795/