Search code examples
c++pointersmfcdialogmdi

Passing CPtrList from a dialog to an MDI Frame


I have an application that builds a grid in an MDI frame from information gathered from a dialog beforehand, however multiple grids are built and I want to be able to select other grids (also built using the information gathered from the dialog) by selecting them from a combo box in the ribbon.

The combo box is populated when the MDI frame is first created, but when I try to select another grid the elements in CPtrList (Created with the dialog) has been deleted; I assume when the dialog is destroyed.

The code in CMainFrame is:

    Cdialog dialog;

if (dialog.DoModal() == IDOK)
{

        CFrame* pFrame;

        BeginWaitCursor();

        CMultiDocTemplate *pDoc = GetDocTemplate(10);
        if (pDoc){

            CBlankDoc* pDocument = (CBlankDoc*)pDoc->CreateNewDocument();
            pDocument->SetTitle("Results");
            pFrame = (CFrame*)pDoc->CreateNewFrame(pDocument, NULL);
            if (pFrame)
            {
                pDoc->InitialUpdateFrame(pFrame, pDocument);
                pFrame->m_plSplits = dialog.GetSplits(); 
                pFrame->m_pParent = this;
                pFrame->m_pMainRibbon = GetRibbonBar();
                pFrame->MDIMaximize();
            }
        }
}

dialog.GetSplits();

looks as follows:

CPtrList* CDialog::GetSplits()
{
    return  &m_plSplits;
}

and

CPtrList* m_plSplits;

Solution

  • You return a pointer to an object that is defined inside the dialog.

    If the pointer inside the CPtrList are still valid after the dialog has been destroyed you can create a copy of the pointer list. But in this case you also need to keep a list inside your frame. Currently you also save a just a pointer.

    Another idea would be to create the pointer list and assign it to a smart pointer (use shared_ptr). Than you can transfer the smart pointer from the dialog and you can assign it to the frame object m_plSplits (this member must be a smart pointer too).

    You have to construct this wisely and you have to determine the lifetime of the inner pointer... CPtrList doesn't destroy anything when the list gets destroyed.

    Maybe just another containter would be a solution like std::list. This container can be copied.