Library tutorials & articles

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.

Comments

  1. 13 Sep 2006 at 07:43

    Sorry posted in wrong thread

  2. 13 Sep 2006 at 06:14
    Hi

    i am new to VC++, while creating a model dialog from a cwnd class i am getting a Assertion error.
    can any one tell me where i did wrong.

    class CAuthen:: public CWnd
    {
      ............
    ..
    public:
     
    CAuthenDlg auth_dlg;
    ..

    public :

     void checkAuthentication();
     

    };

    void CAuthen :: checkAuthentication()
    {
    ..
    ..
    ..

       if(  auth_dlg.DoModal() == IDOK)
        {
           ...
           // some operation goes here
        }
    ..
    ..
    }



































  3. 01 Jan 1999 at 00:00

    This thread is for discussions of Attaching and Detaching Objects.

Leave a comment

Sign in or Join us (it's free).

Joseph M. Newcomer

We'd love to hear what you think! Submit ideas or give us feedback