【问题标题】:C++ memory leaks by static variable [duplicate]静态变量导致C ++内存泄漏[重复]
【发布时间】:2013-10-15 16:56:33
【问题描述】:

Visual Studio 2012 告诉我以下程序存在内存泄漏。这是正确的吗?如果是这样,在使用(例如)静态向量时如何避免内存泄漏?

#include <crtdbg.h>
#include <vector>

struct A {
  static std::vector<int> a;
};
std::vector<int> A::a;

int main()
{
  _CrtDumpMemoryLeaks();
    return 0;
}

【问题讨论】:

  • 它正在报告“泄漏”,因为您调用它为时过早。如果您删除对_CrtDumpMemoryLeaks 的调用并在调试中运行,您会收到任何泄漏报告吗?
  • @RogerRowland 如果我错了,请纠正我,但这不是生成内存泄漏报告的必要条件吗?

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


【解决方案1】:

您在静态变量的作用域完成之前调用该函数。因此,您期望变量已被破坏是错误的。

在调用该函数之前,您需要等到范围结束。当然这很难做到,但运行时可以帮助您,如documentation 中所述:

通过使用 _CrtSetDbgFlag 函数打开 _crtDbgFlag 标志的 _CRTDBG_LEAK_CHECK_DF 位字段,可以在程序终止时自动调用该函数。

【讨论】:

    猜你喜欢
    • 2011-02-15
    • 1970-01-01
    • 2013-11-06
    • 1970-01-01
    • 1970-01-01
    • 2014-06-19
    • 2013-07-26
    • 2010-10-25
    • 2010-10-13
    相关资源
    最近更新 更多