enum DataType
{
DATA_INT,
DATA_STRING
};
class GameMessage
{
public:
GameMessage( DataType Type, void* pData )
{
switch( Type )
{
case DATA_INT:
m_pData = new int;
*(int*)m_pData = *(int*)pData;
break;
case DATA_STRING:
m_pData = new std::string;
*(std::string*)m_pData = *(std::string*)pData;
break;
}
m_DataType = Type;
}
~GameMessage()
{
delete m_pData; // Is this correct?
// Or maybe I should do:
switch( m_DataType )
{
case DATA_INT:
delete (int*)m_pData;
break;
case DATA_STRING:
delete (std::string*)m_pData;
break;
}
}
void* m_pData;
DataType m_DataType;
};
Deleting void pointers
Is it safe to delete a void pointer without casting it to its base type? Will it always delete the right amount of memory? Assume that I never allocate arrays, only single objects. For example:
Your example should work, memory is allocated by blocks
(look the malloc and free functions, they use void* )
(look the malloc and free functions, they use void* )
No! new and delete are different to malloc and free because they call constructors and destructors. If you delete a pointer to a non-POD type via a void * the destructor will not be called! Don't circumvent the type system. Use something like boost::variant if you really need differing data types or rethink your design.
Enigma
Enigma
deleting a void pointer is bad, as it won't know what deconstructor to invoke. Using free is also bad; never mix new/free or malloc/delete. If you must, cast it to the correct type and delete that.
Quote:Original post by Arcibald Wearlot
Is it safe to delete a void pointer without casting it to its base type? Will it always delete the right amount of memory?
No. It's not safe. It has undefined behaviour. Which means that compiler writers are allowed to assume you will never do that. They don't have to test for that case, don't have to flag it as an error.
... a bit when people write IO routines that expect a number and somebody comes in and types text ...
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement