Re: CListCtrl, custom item data and allocation policy
On Wed, 16 Jan 2008 14:27:50 -0600, "Doug Harrison [MVP]" <dsh@mvps.org>
wrote:
That's up to you. Your CMyListCtrl could maintain a flag that indicates
whether or not it should delete item data for items that are removed from
the list. You could initialize this flag with a ctor parameter.
That'll work for item data allocated with malloc() that can be free()'d but
not for C++ types that must be deleted. The problem is that pointer item
data is void*, and you have to cast it to the correct type before you can
delete it. A general solution would be to define an abstract "Deleter"
class, derive various concrete classes, and pass pointers to these objects
to the CMyListCtrl, e.g.
struct AbstractDeleter
{
virtual void Delete(void*) = 0;
};
template<typename T>
struct ConcreteDeleter : AbstractDeleter
{
void Delete(void* p)
{
delete static_cast<T*>(p);
}
};
class MyDialog
{
MyDialog()
: c_list(&m_deleter)
{
}
ConcreteDeleter<SomeType> m_deleter;
CMyListCtrl c_list;
};
Now if the c_list has a non-NULL AbstractDeleter object, it knows it has to
delete the item data, and it can do so, even though it has no idea what the
ConcreteDeleter does in its implementation of Delete().
Another approach is for the dialog to handle the LVN_DELETEITEM and
LVN_DELETEALLITEMS notifications. Still another is to use a virtual
listview and maintain all the list data in an array instead of using
per-item data.
--
Doug Harrison
Visual C++ MVP