Weird behaviour of C++ destructors(C++ 析构函数的奇怪行为)
问题描述
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< vector<int> > dp(50000, vector<int>(4, -1));
cout << dp.size();
}
这个小程序只需从命令行运行就需要几秒钟的时间来执行.但是当在调试器中运行时,它需要超过 8 秒.暂停调试器表明它正在销毁所有这些向量.跆拳道?
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.
添加: 澄清一下,不,我没有混淆调试和发布版本.这些结果在同一个 .exe 上,中间甚至没有任何重新编译.事实上,在 Debug 和 Release 版本之间切换没有任何改变.
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++ 析构函数的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 析构函数的奇怪行为
基础教程推荐
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- Windows Media Foundation 录制音频 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01