Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 views
in Technique[技术] by (71.8m points)

c++ - How to delete void pointer?

Is there anything wrong when deleting an object like this in C++?

MyCls* c = new MyCls();
void* p = (void*)c;
delete (MyCls*)p;
question from:https://stackoverflow.com/questions/24772699/how-to-delete-void-pointer

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This as written is legal.

The cast back to MyCls* is critical. Without that, you will invoke undefined behavior--the MyCls destructor will not be called, and other problems may arise as well (such as a crash). You must cast back to the correct type.

Also note that this can be complicated if multiple inheritance is involved and multiple casts are used. Your casts must "match" in either direction.

If your code is structured such that you won't know the type at the time of destruction, give each deletable object a common base class with a virtual destructor. Then cast back to the base class before delete is called.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...