const void
is allowed simply because there is no point making the compiler kick out this one exception to a general rule and it does no harm to leave it in.
There is some discussion above that const void*
is not very useful:
How useful is const void *? I can see how void * const could be, but not the former. –Spidey
In fact const void*
is sometimes essential.
It declares that the thing being pointed to is read only as opposed to void* const
which only declares that the pointer itself is constant but not the thing it points to.
From my experience, the pointer to constant using const void*
is the more useful of the two forms. Of course, there is also const void* const
meaning that both the pointer and the thing it points to are constant.
void*
is normally used as a way to pass non-specific pointers around (e.g. with memcpy()
).
If you want to pass a const char*
to such a function then you cannot use void*
or you lose the fact that the thing it points to is constant and cannot be altered. Current C++ compilers will refuse to compile that as it would have to implicitly cast the const
away, and rightfully so as this data might be in read-only memory and possibly cause an exception if anything tries to write to it.
This is why the second argument to memcpy()
is const void*
and not simply void*
.
const
in a function pointer lookup table. There were three possible locations. One of them failed to compile, and the outermostconst
clearly declared an array of pointers to functions returningconst void
, and I was surprised the compiler accepted that code.