附加调试器时,可以慢慢调用unique_ptr dtor(msvc)

时间:2012-05-21 05:43:18

标签: c++ debugging visual-c++ unique-ptr

struct test_struct
{
    test_struct() {}
    ~test_struct() {}
};

#include <vector>
#include <memory>
#include <cstdio>

int main()
{
    printf("ctor begin\n");
    {
        std::vector<std::unique_ptr<test_struct>> test_vec;
        const int count = 100000;

        for (auto i = 0; i < count; i++) {
            test_vec.emplace_back(new test_struct);
        }
        printf("dtor begin\n");
    }
    printf("dtor end\n");
}

我正在使用VS2010,并发现了一些荒谬的性能问题。上面的代码在调试和发布版本(ctrl + f5)中运行良好,但是当附加调试器时(f5),dtor对unique_ptr类的调用是无法忍受的。结果机器代码是相当优化的,所以我不期望它是编译器问题而不是调试器,但我不知道如何处理它。我的问题是

  • 是否可以在您的机器上重现此问题?
  • 这种行为的原因是什么?
  • 有解决方法吗?

1 个答案:

答案 0 :(得分:6)

减速是由释放内存时发生的内存检查引起的。但是,这是一个特殊的系统/调试器级堆,并不是您可以在程序中控制的任何内容。

有一个great article on the issue。总结一下:你必须设置一个环境变量来禁用它!

幸运的是,您可以从项目的“项目设置”中的“调试”选项中设置项目特定的环境变量,以便环境变量仅应用于您的程序。

我用这个简化的程序来测试:

#include <iostream>
#include <memory>
#include <vector>

int main()
{
    std::cout << "ctor begin" << std::endl;
    {
        std::vector<std::unique_ptr<int>> test_vec;

        for (unsigned i = 0; i < 100000; i++)
            test_vec.emplace_back(new int);

        std::cout << "dtor begin" << std::endl;
    }
    std::cout << "dtor end" << std::endl;
}

通过将_NO_DEBUG_HEAP=1设置为环境变量(系统范围,我不建议或通过调试选项),代码运行的时间大致相同,无论是否调试器已附加。