Sign in to follow this  

delete a casted void pointer ?

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

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