This is kind of basic but I can't seem to get a hold on this one. Reference here
Are void *p
and const void *p
sufficiently different? Why would a function use const void *
instead of void *
?
This is kind of basic but I can't seem to get a hold on this one. Reference here
Are void *p
and const void *p
sufficiently different? Why would a function use const void *
instead of void *
?
The reason to use void*
at all (whether const
or not) is the kind of genericity is provides. It's like a base class: All pointers are void*
and can implicitly cast into it, but casts from void*
to typed pointers have to be done explicitly and manually.
Usually, C++ has better ways to offer to do this (namely OO and templates), so it doesn't make much sense to use void*
at all, except when you're interfacing C. However, if you use it, then const
offers just what it offers elsewhere: you need an (additional) const_cast
to be able to change the object referred to, so you are less likely to change it accidentally.
Of course, this relies on you not employing C-style casts, but explicit C++ casts. The cast from void*
to any T*
requires a static_cast
, and this doesn't allow removing of const
. So you can cast const void*
to const char*
using static_cast
, but not to char*
. This would need an additional const_cast
.
There is a simple difference. As other stated, there is little need to use void*
in C++ due to its better type system, templates, etc. However, when interfacing to C or to system calls, you sometimes need a way to specify a value without a known type.
As you ask, the difference between void*
and const void*
is a hint to show you if the contents of the pointed memory will be modified within the function you're calling, the const
meaning it will have a read-only access.
In c++ a const in front of a pointer says the data at the pointer's address should not be changed. i.e. it stops someone doing this:
int v1 = 3;
int v2 = 4;
const int *pv = &v1;
pv = &v2 // ok;
*pv = 5; // error
You can also make the pointer value itself a const:
int v1 = 3;
int v2 = 4;
int * const pv = &v1;
*pv = 5; // ok
pv = &v2; // error
You can also combine the two:
int v1 = 3;
int v2 = 4;
const int * const pv = &v1;
*pv = 5; // error
pv = &v2; // error