Jump to content
  • Advertisement
Sign in to follow this  
Arcibald Wearlot

Deleting void pointers

This topic is 5050 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
Advertisement
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
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.

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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!