静态变量导致的 C++ 内存泄漏

标签 c++ visual-studio-2012 memory-leaks static

<分区>

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/

相关文章:

c++ - 单例类和多重继承

c++ - 使用 C++ 输出运算符打印前导零?

c++ - 如何在 MS 编译器中用数组初始化 C++ vector/集合?

iphone - 奇怪的内存泄漏

c++ - 忽略 SIGSEGV 并继续执行

c++ - 如何在exe中包含所有dll?

c - 如何在 windows VS2012 或 VS2010 上设置 GStreamer Editing Services 1.2.0 (GES) 环境

java - 在最近的 JVM 中,不可见的引用仍然是一个问题吗?

python - 在 Python 中丢弃图像时内存泄漏

c++ - c++11/1y lambda 函数的类型签名是什么?