奇怪的C ++析构函数的行为 [英] Weird behaviour of C++ destructors

查看:138
本文介绍了奇怪的C ++析构函数的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    vector< vector<int> > dp(50000, vector<int>(4, -1));
    cout << dp.size();
}

这个小程序从命令行运行时需要一秒时间执行。但是当在调试器中运行时,它需要8秒钟。暂停调试器显示它正在破坏所有这些向量。 WTF?

This tiny program takes a split second to execute when simply run from the command line. But when run in a debugger, it takes over 8 seconds. Pausing the debugger reveals that it is in the middle of destroying all those vectors. WTF?

注意 - Visual Studio 2008 SP1,Core 2 Duo 6700 CPU,2GB RAM。

Note - Visual Studio 2008 SP1, Core 2 Duo 6700 CPU with 2GB of RAM.

strong> Added:为了澄清,不,我不会混淆Debug和Release builds。这些结果在同一个.exe上,甚至没有任何重新编译。

Added: To clarify, no, I'm not confusing Debug and Release builds. These results are on one and the same .exe, without even any recompiling inbetween. In fact, switching between Debug and Release builds changes nothing.

推荐答案

在调试器中运行会将内存分配库更改为一个做了很多检查。

Running in the debugger changes the memory allocation library used to one that does a lot more checking. A program that does nothing but memory allocation and de-allocation is going to suffer much more than a "normal" program.

编辑
刚刚在VS下运行你的程序,我得到一个看起来像

Edit Having just tried running your program under VS I get a call stack that looks like

ntdll.dll!_RtlpValidateHeapEntry@12()  + 0x117 bytes    
ntdll.dll!_RtlDebugFreeHeap@12()  + 0x97 bytes  
ntdll.dll!_RtlFreeHeapSlowly@12()  + 0x228bf bytes  
ntdll.dll!_RtlFreeHeap@12()  + 0x17646 bytes    
msvcr90d.dll!_free_base(void * pBlock=0x0061f6e8)  Line 109 + 0x13 bytes
msvcr90d.dll!_free_dbg_nolock(void * pUserData=0x0061f708, int nBlockUse=1)
msvcr90d.dll!_free_dbg(void * pUserData=0x0061f708, int nBlockUse=1) 
msvcr90d.dll!operator delete(void * pUserData=0x0061f708)
desc.exe!std::allocator<int>::deallocate(int * _Ptr=0x0061f708, unsigned int __formal=4)
desc.exe!std::vector<int,std::allocator<int> >::_Tidy()  Line 1134  C++

这显示了ntdll.dll中的调试功能, C运行时。

Which shows the debug functions in ntdll.dll and the C runtime being used.

这篇关于奇怪的C ++析构函数的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆