CFont::FromHandle(HFONT) returns a CFont* that wraps the HFONT. The MFC documentation states that:
If a
CFontobject is not already attached to the handle, a temporaryCFontobject is created and attached. This temporaryCFontobject is valid only until the next time the application has idle time in its event loop, at which time all temporary graphic objects are deleted. Another way of saying this is that the temporary object is valid only during the processing of one window message.
But it does not clarify if the temporary CFont object will call DeleteObject() on the HFONT when it is deleted.
Does CFont::FromHandle(HFONT) assume ownership of the HFONT?
And if so, what happens if that HFONT is already wrapped by different CFont instance?
In context: I'm working with legacy code that has a "font manager" object that I ask for the appropriate font. I know that internally the font manager stores the fonts as CFont instances, but its methods just hand them out as HFONT.
So I have code like this:
{
CDC* pDC = GetDC();
HFONT fontH = myFontManager->GetTheRightFont(state);
CFont* newFont = CFont::FromHandle(fontH);
CFont* oldFont = pDC->SelectObject(newFont);
..
// draw some stuff
..
pDC->SelectObject(oldFont);
ReleaseDC(pDC);
}
My concern is that when the temporary newFont is deleted it will call DeleteObject() on fontH possibly leaving myFontManager with a CFont member instance that wraps a font handle that is no longer valid.
Note: I've read https://www.codeproject.com/Articles/535/Attaching-and-Detaching-Objects but I am no clearer how that applies to FromHandle.