Attaching and Detaching Objects

Dissociating Wrappers

One solution often used by programmers is the following:

{
 CFont * f;
 f = new CFont;
 f->CreateFont(...);
 c_EditControl.SetFont(f);
}

Empirical observation demonstrates that this code works, and works correctly. This is true. It works. But it is sloppy code. What, exactly, happened to that CFont object referenced via the CFont *? Nothing, that's what happened. There is a rogue CFont out there, unreachable, and undestroyable. It will stay around forever. This might be harmless, but it is not good programming practice.

What I do is as follows, and this is a very important trick when you are using MFC at the MFC-to-Windows interface. I use the Detach method:

{
    CFont f;
    f.CreateFont(...);
    c_InputData.SetFont(&f);
    f.Detach(); // VERY IMPORTANT!!!
}

The Detach operation dissociates the Windows object from its wrapper, and returns as its value the underlying Windows object handle. Since I don't need it, I don't bother to assign it to anything. But now, when the CFont is destroyed, the associated m_hObject handle is NULL and the underlying HFONT is not destroyed.

If you were to read my code, you'd find lots of instances of Detach inside. An example is my window bitmap capture function, which gets a bitmap for a specified window and puts it in the clipboard. In order to keep the bitmap from being destroyed on scope exit, it detaches the bitmap from the CBitmap object.

You might also like...

Comments

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“If Java had true garbage collection, most programs would delete themselves upon execution.” - Robert Sewell