【发布时间】:2010-10-03 16:23:51
【问题描述】:
我注意到使用任务管理器时,以下代码中存在 GDI 泄漏。执行此代码的进程中 GDI 对象的计数每次执行时都会增加 1,但我似乎找不到问题。
任何帮助将不胜感激。
// create new DC based on current
HDC hDC = CreateCompatibleDC(GetDC());
// select a bitmap into the new DC and keep the old one
HGDIOBJ hOldObj = SelectObject (hDC,hBM);
// do somthing here --> 100% no leak here
SomeFunction (hDC);
// select the old object back from whence it came and delete whats returned
DeleteObject (SelectObject (hDC,hOldObj));
// delete the DC
DeleteDC(hDC);
// delete the tmp object
DeleteObject (hOldObj);
RM
【问题讨论】:
-
一般来说嵌套调用不是一个好主意,即 HDC hDC1 = GetDC(); HDC hDC2 = CreateCompatibleDC(hDC1); .. 而不是 HDC hDC = CreateCompatibleDC(GetDC()); (顺便说一句,在您的代码中,GetDC 返回的 HDC 未被释放。)
-
xhantt:这不是答案吗?把评论删掉,放到回答区。
-
所以修复只是针对 getDC 返回的 ReleaseDC 吗?如果我理解正确,请在答案部分写下这个答案,以便我们投票。
-
顺便说一句,不要
DeleteObject(hOldObj)。那不是你要清理的对象。你没有创建它,所以不要删除它。 -
你可以使用 valgrind 或 deleaker。但是deleaker这个名字不言自明)