简体   繁体   English

指向无效的指针

[英]pointer to 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? void *pconst void *p足够不同? Why would a function use const void * instead of void * ? 为什么函数使用const void *而不是void *

The reason to use void* at all (whether const or not) is the kind of genericity it provides. 完全使用void* (无论是否为const )的原因是它提供的通用性。 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. 这就像一个基类:所有指针都是 void* ,可以隐式转换为它,但是从void*到类型化指针的转换必须显式且手动进行。

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. 通常,C ++提供了更好的方法来执行此操作(即OO和模板),因此,除非您与C相连,否则根本不要使用void* 。但是,如果使用C,则使用const在其他地方提供它提供的功能:您需要一个(附加) const_cast才能更改所引用的对象,因此不太可能意外更改它。

Of course, this relies on you not employing C-style casts, but explicit C++ casts. 当然,这不依赖于您不采用C样式强制转换,而是显式C ++强制转换。 The cast from void* to any T* requires a static_cast , and this doesn't allow removing of const . void*到任何T*需要static_cast ,这不允许删除const So you can cast const void* to const char* using static_cast , but not to char* . 因此,您可以使用static_castconst void* static_castconst char* ,而不能static_castchar* This would need an additional const_cast . 这将需要一个额外的const_cast

In c++ a const in front of a pointer says the data at the pointer's address should not be changed. 在c ++中,指针前面的const表示不应更改指针地址处的数据。 ie 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: 您还可以使指针值本身为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. 如前所述,由于C ++具有更好的类型系统,模板等,因此在C ++中几乎不需要使用void* 。但是,当与C或系统调用接口时,有时需要一种方法来指定没有已知类型的值。

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. 正如您所问的那样, void*const void*之间的区别是一个提示,向您显示是否将在所调用的函数内修改指向内存的内容, const意味着它将具有只读访问权限。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM