C++ 资源泄漏-设备上下文太多
我有一个正常工作的C++/Windows程序,我注意到它有一个图形资源泄漏。我使用它并追踪到设备上下文的构建 进一步看,我跟踪到一对行,见注释a行和B行,如下所示:C++ 资源泄漏-设备上下文太多,c++,winapi,windows-7-x64,C++,Winapi,Windows 7 X64,我有一个正常工作的C++/Windows程序,我注意到它有一个图形资源泄漏。我使用它并追踪到设备上下文的构建 进一步看,我跟踪到一对行,见注释a行和B行,如下所示: hdc = BeginPaint(hwnd,&global_paintstruct); handle_of_source_device_context = CreateCompatibleDC(GetDC(0)); // Line A #if 0 // temporarily while debugging // stu
hdc = BeginPaint(hwnd,&global_paintstruct);
handle_of_source_device_context = CreateCompatibleDC(GetDC(0)); // Line A
#if 0 // temporarily while debugging
// stuff using handle_of_source_device_context
#endif
DeleteDC(handle_of_source_device_context); // Line B
EndPaint(hwnd,&global_paintstruct);
如果我注释掉A和B行,那么就没有资源泄漏
我测试了DeleteDC是否返回1
有什么想法吗?根据GetDC的返回值调用ReleaseDC:
dc = GetDC(0)
...
ReleaseDC(dc);
当不再需要使用ReleaseDC来防止GDI泄漏时,您需要调用ReleaseDC for DC。代码的固定版本如下所示:
hdc = BeginPaint(hwnd,&global_paintstruct);
HDC hWndDC = GetDC(NULL);
handle_of_source_device_context = CreateCompatibleDC(hWndDC); // Line A
#if 0 // temporarily while debugging
// stuff using handle_of_source_device_context
#endif
ReleaseDC(hWndDC);
ReleaseDC(handle_of_source_device_context);
DeleteDC(handle_of_source_device_context); // Line B
EndPaint(hwnd,&global_paintstruct);
我认为您还必须释放GetDC返回的句柄。您也是这样做的。在:使用公共DC绘制后,必须调用ReleaseDC函数来释放DC。您也可以使用WTL智能指针:CClientDC和DCWhy you calling CreateCompatibleDCGetDC0,而不是CreateCompatibleDChdc?@和实验室:剪切和粘贴我不完全理解的其他人的代码。是的,刚刚试用了你的版本,效果很好:-