-
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.
-
1 Attachment(s)
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