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?
It offers the same benefit that const
offers on other pointer types: you can't modify what is pointed to unless you cast away the const
-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::memcpy
is declared as
void *memcpy(void *dest, const void *src, std::size_t count);
which signals that it will read src
and write to dest
. 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 const
keyword per se that apparently has no value.