When you have a class object derived from CWnd
and you call object.GetDC()
, but it returns a nullptr
, do you still need to call object.releaseDC()
with the nullptr
?
I have a function that calls GetDC
and ReleaseDC
as such:
CDC* const pDC = m_wndRibbonBar.GetDC();
if (!pDC)
{
return;
}
//... (draw some stuff here)
m_wndRibbonBar.ReleaseDC(pDC);
Currently I'm not having any issues since GetDC()
always returns a valid pointer but if it didn't, would I need to call ReleaseDC(pDC)
with the nullptr
before the early return?
As noted in the comments and the answer, you should check the documentation. If the operation failed you don't have a valid CDC*
, so what's the point of calling ReleaseDC()
?.
Apart from that you can always check the MFC sources if you are not sure. The CWnd::ReleaseDC()
implementation is inline, and can be found in file afxwin2.inl:
_AFXWIN_INLINE int CWnd::ReleaseDC(CDC* pDC)
{ ASSERT(::IsWindow(m_hWnd)); return ::ReleaseDC(m_hWnd, pDC->m_hDC); }
That is, it calls the Win32 ReleaseDC()
function, with the window's and DC's handles. You must have a valid windows handle for the operation to succeed (the assertion will only fail for debug builds though). But pDC->m_hDC
will cause a run-time error (access violation or null pointer reference) if pDC
is NULL. So you should NOT call ReleaseDC()
with a NULL pDC
.