CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 2 of 2 FirstFirst 12
Results 16 to 17 of 17
  1. #16
    Join Date
    Apr 2003
    Location
    UK
    Posts
    83
    Yes, your code is how it should be done - but check for a NULL pointer (just in case):

    Code:
    nIndex = 0;
    CPerson* pPerson = m_myListBox.GetItemDataPtr(nIndex);
    
    if (pPerson != NULL)
    {
        CString strName = pPerson->m_strName;
    }
    This is getting the address for the previously allocated person and assigning it to a local pointer. If you look at the value of pPerson here, you should see it matches the same address of pPerson when you called SetItemDataPtr for row 0.

    You should delete the allocated memory in the destructor for the class which owns m_myListBox; I assume this is your view class, something like this,

    Code:
    CMyView::~CMyView()
    {
        for (int nIndex = 0; nIndex < m_myListBox.GetCount(); nIndex++)
        {
            CPerson* pPerson = m_myListBox.GetItemDataPtr(nIndex);
    
            if (pPerson != NULL)
            {
                delete pPerson;
            }
        }
    }
    If you don't do this you'll get memory leaks. CListBox does not do this for you - it assumes you (i.e., your view) know best when to free memory that you (the view) allocated.

    Generally it is good coding practice to free memory in the same object where it was originally allocated. That object (e.g., your view class) is the owner of the memory, and therefore should be responsible for freeing it.

  2. #17
    Join Date
    Oct 2003
    Location
    Athens
    Posts
    231
    You should delete the allocated memory in the destructor for the class which owns m_myListBox; I assume this is your view class, something like this,

    Code:
    CMyView::~CMyView()
    {
        for (int nIndex = 0; nIndex < m_myListBox.GetCount(); nIndex++)
        {
            CPerson* pPerson = m_myListBox.GetItemDataPtr(nIndex);
    
            if (pPerson != NULL)
            {
                delete pPerson;
            }
        }
    }
    If you don't do this you'll get memory leaks. CListBox does not do this for you - it assumes you (i.e., your view) know best when to free memory that you (the view) allocated.


    Hi astanley or anyone else that can help:
    I have tried this but it doesn't seem to work....I keep getting assertions when i close the program. I applied the advise you gave above but it still gives errors, please any advise will be very helpful.


    Thanks in advance
    I have attached the program
    Attached Files Attached Files

Page 2 of 2 FirstFirst 12

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured