开发者

pointer to void

开发者 https://www.devze.com 2023-01-16 05:54 出处:网络
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 diff开发者_Python百科erent? Why would a function use const void * instead

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 diff开发者_Python百科erent? 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 it 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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号