In C++, is there any value in using a const void * for an argument type to a function over a void *? Since a void * is opaque, is there any risk of modification other than if the user does reinterpret_cast, in which case they could likewise do const_cast on a const void * and thus does one really buy anything? I ask because I was using a utility template class for shared pointers which provided a specialization on void to avoid void & issue but no specialization was provided for const void and thus I wonder whether this was just an oversight or should it never be needed?
In C++, is there any value in using a const void * for an
Share
It offers the same benefit that
constoffers on other pointer types: you can’t modify what is pointed to unless you cast away theconst-ness explicitly. In interfaces,const void*is a sign to client code that whatever you pass in may be read but not written to. E.g.,std::memcpyis declared aswhich signals that it will read
srcand write todest. Of course, if it were really implemented in C++ (possible but not likely), it has to cast both pointers to other types.If you feel that this “doesn’t buy you anything”, then it’s the
constkeyword per se that apparently has no value.