读书人

内存储器为什么不泄露

发布时间: 2012-09-08 10:48:07 作者: rapoo

内存为什么不泄露

C/C++ code
#include "stdafx.h"#include <Windows.h>#include <string>HANDLE    g_hwnd=NULL;DWORD    g_ExitCode=0;DWORD WINAPI ThreadFun(LPVOID lpThreadParameter ){    #ifdef _DEBUG        CheckMemoryLeak;#endif    std::string str="hello";  //它 的析构函数貌似也会调用,应该不会啊    Sleep(5000);    ExitThread(g_ExitCode);    printf("xyz\n");    return 0;}int main(){#ifdef _DEBUG    CheckMemoryLeak;#endif    g_hwnd=CreateThread(NULL,0,ThreadFun,NULL,0,NULL);    GetExitCodeThread(g_hwnd,&g_ExitCode);    WaitForSingleObject(g_hwnd,-1);    CloseHandle(g_hwnd);    return 0;}


这代码是故意来看ExitThread是否会造成资源泄露的,结果发现不会。

是怎么回事呢?



[解决办法]
ExitThread is the preferred method of exiting a thread. When this function is called (either explicitly or by returning from a thread procedure), the current thread's stack is deallocated and the thread terminates. The entry-point function of all attached dynamic-link libraries (DLLs) is invoked with a value indicating that the thread is detaching from the DLL.

If the thread is the last thread in the process when this function is called, the thread's process is also terminated.

[解决办法]
vc的std::string有个优化: 字符串长度小于16,则不在堆上开辟空间, std::string对象内部有个长度16的字符数组。显然"hello"小于16,所以没有泄露。

请尝试创建一个更长的字符串。
[解决办法]
如你所想, std::string的析构函数并没有调用,可以看看反汇编看看。

读书人网 >C语言

热点推荐