Is void* necessary apart from memory allocation related stuff in C++?
Can you give me an example?
Is void* necessary apart from memory allocation related stuff in C++? Can you give
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Logging memory addresses
If you want to output a pointer using iostreams (e.g. for logging) then going via
void*is the only way of ensuringoperator<<hasn’t been overloaded in some crazy way.Testing iostream status
iostreams overload
operator void*as a status check so that syntax likeif (stream)orwhile (stream)is a short hand way of testing the stream status.Template meta programming
You might want to use
void*with template metaprogramming sometimes as a reduced catch all, e.g. with SFINAE tricks, but more often than not there’s a nicer way around it using a partial specialisation of one form or another.Accessing most derived pointer
As Alf pointed out in the comments
dynamic_cast<void*>is also useful for getting at the most derived type in a heirarchy, e.g.:Gives:
On my system.
Exceptions
§ 15.3.1 states:
So it seems to be the only legal way of catching a pointer to an incomplete type is via
void*. (Although I think there’s possibly bigger issues if you actually needed to use that)Legacy C uses
There are a lot of “legacy” C uses for
void*for storing pointers to data without knowing what it is, but in new C++ code there is almost always a better way of expressing the same functionality.