指针void [英] pointer to void

查看:168
本文介绍了指针void的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个基本的,但我似乎不能抓住这一个。参考此处

This is kind of basic but I can't seem to get a hold on this one. Reference here

void * p const void * p 有什么区别吗?为什么函数使用 const void * 而不是 void *

Are void *p and const void *p sufficiently different? Why would a function use const void * instead of void *?

推荐答案

所有使用 void * 的原因(是否 const 或不)是它提供的一种类型。它就像一个基类:所有的指针都是 void * ,并且可以隐式地转换为它,但是从 void * / code>到类型指针必须显式和手动完成。

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.

通常,C ++有更好的方法来提供这样做(即OO和模板),所以使用 void没有什么意义* ,但是当你连接C.但是,如果你使用它,然后 const 提供它在其他地方:一个(附加的) const_cast 以便能够更改所引用的对象,因此您不太可能意外更改它。

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风格的转换,而是使用显式的C ++转换。从 void * 到任何 T * 的转型需要 static_cast ,并且这不允许删除 const 。因此,您可以使用 static_cast const void * 转换为 const char * c>,但不是 char * 。这需要一个额外的 const_cast

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.

这篇关于指针void的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆