Sign in to follow this  

Deleting void pointers

This topic is 4686 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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:

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;
};



Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
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 ...

Share this post


Link to post
Share on other sites

This topic is 4686 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this