Question

I have a very simple class which notifies parent thread when a function in thread is complete. The problem is when instantiate it, constructor is called and then immediately the destructor is called. Here is the class:

AutoNotify::AutoNotify(HWND hWnd)
{
    m_hWnd = hWnd;

    ::PostMessage( m_hWnd, IDM_THREAD_STARTED, 0 , 0 );
}

AutoNotify::~AutoNotify(void)
{
    ::PostMessage( m_hWnd, IDM_THREAD_FINISHED, 0 , 0 );
}

Here is how I am using this class in another class.

UINT CTestDlg::ThreadProc( LPVOID lpVoid)
{
    int result = false;

    CTestDlg *dlg = (CTestDlg *) lpVoid;

    AutoNotify( dlg->m_hWnd );

    if ( (result = dlg->LongFunction()) == ERROR_SUCCESS )
        return result;

    // more stuff

    return TRUE;
}

When I step through the debugger, it calls the AutoNotify constructor and then immediately its destructor. I figured maybe because of some compiler optimization because the class is empty!? Than I declare its only member variable m_hWnd as volatile but still no use. Anyone why is the destructor called in immediately?

Was it helpful?

Solution

The destructor is called right away because this line

AutoNotify( dlg->m_hWnd );

creates a temporary object that gets deleted right away.

This line creates a non-temporary object:

AutoNotify guard( dlg->m_hWnd );

Now the destructor will be called only when the guard object goes out of scope.

OTHER TIPS

AutoNotify(dlg->m_hWnd);

That is a call to your constructor. It creates a temporary object which is immediately destroyed. You would typically write:

AutoNotify a(dlg->m_hWnd);

Now it's a named object and will survive until the end of the function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top