Jump to content
  • Advertisement
Sign in to follow this  
fantasyz

delete a casted void pointer ?

This topic is 4486 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

Can i delete a casted void pointer like the code below? The program can be complied without error but i am not sure if there is any problem i can't see.

void* pData = new ARandomClass;

/*Do something*/

delete (ARandomClass*) pData;


thankyou

Share this post


Link to post
Share on other sites
Advertisement
Yes, you can do that. However, if you know what the type is, it shouldn't be a void* to begin with.

Share this post


Link to post
Share on other sites
I would use a C++ cast. Even then, you'd need a reinterpret_cast.

The real problem here comes from the fact that you're using a void pointer - why?

Share this post


Link to post
Share on other sites
Yes, with class polymorphism and templates, there's very little reason to use void pointers. You lose all type information when you cast to void*, best to avoid that. Also, if you accidentally cast to the wrong type, "bad things" would happen when you tried to delete it, especially if the class' dtor deletes anything else or does any system or API calls.

Share this post


Link to post
Share on other sites
Thankyou for the replies first.

My situation is that I have a list of pointer pointing to some objects within the same group (they are different classes but they all extend a CustBase class containing common attributes. I can use a flag in CustBase class to identify their real class.)

Since one list cannot store different type of object, i use CustBase pointer to do solve this problem.
( and I don want to use several lists to store the group)

Actually, my list is not a void pointer list. I just use void pointer in the example.

well...Is there any better ways to do the job?

Share this post


Link to post
Share on other sites
Yes, store pointers to CustBase objects in your list. Also, make sure it has a virtual destructor. Then you can call delete on the CustBase* and it will properly destroy the object.

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.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!