void* 和 void** 的心智模型?
注意:我是一名经验丰富的 C++ 程序员,因此我不需要任何指针基础知识。只是我从未使用过 void**
并且很难将我的心理模型调整为 void*
与 void**
>。我希望有人能以一种好的方式解释这一点,以便我可以更容易地记住语义。
考虑以下代码:(使用 VC++ 2005 等进行编译)
int main() {
int obj = 42;
void* ptr_to_obj = &obj;
void* addr_of_ptr_to_obj = &ptr_to_obj;
void** ptr_to_ptr_to_obj = &ptr_to_obj;
void* another_addr = ptr_to_ptr_to_obj[0];
// another_addr+1; // not allowed : 'void*' unknown size
ptr_to_ptr_to_obj+1; // allowed
}
Note: I'm a experienced C++ programmer, so I don't need any pointer basics. It's just that I never worked with void**
and have kind of a hard time getting my mental model adjusted to void*
vs. void**
. I am hoping someone can explain this in a good way, so that I can remember the semantics more easily.
Consider the following code: (compiles with e.g. VC++ 2005)
int main() {
int obj = 42;
void* ptr_to_obj = &obj;
void* addr_of_ptr_to_obj = &ptr_to_obj;
void** ptr_to_ptr_to_obj = &ptr_to_obj;
void* another_addr = ptr_to_ptr_to_obj[0];
// another_addr+1; // not allowed : 'void*' unknown size
ptr_to_ptr_to_obj+1; // allowed
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
void*
是一个指向某个东西的指针,但你不知道是什么。因为你不知道它是什么,也不知道它占用了多少空间,所以你不能递增指针。void**
是一个指向void*
的指针,因此它是一个指向指针的指针。我们知道空间指针占用了多少空间,因此我们可以增加void**
指针以指向下一个指针。void*
is a pointer to something, but you don't know what. Because you don't know what it is, you don't know how much room it takes up, so you can't increment the pointer.void**
is a pointer tovoid*
, so it's a pointer to a pointer. We know how much room pointers take up, so we can increment thevoid**
pointer to point to the next pointer.void*
指向编译器未知其类型的对象。void**
指向存储这样一个void*
的变量。A
void*
points to an object whose type is unknown to the compiler.A
void**
points to a variable which stores such avoid*
.void *
可以指向任何东西(函数除外)。所以它甚至可以指向指针,因此它甚至可以指向其他void *
对象。void **
是一个指向void *
的指针,因此它只能用于指向void *对象。
A
void *
can point at anything (except functions). So it can even point at pointers, so it can even point at othervoid *
objects.A
void **
is a pointer-to-void *
, so it can only be used to point atvoid *
objects.void
具有误导性,因为它听起来像null
。但是,最好将void
视为未指定的类型。因此,void*
是未指定类型的指针,void**
是指向未指定类型的指针。void
is misleading because it sounds likenull
. However, it's better to think ofvoid
as an unspecified type. So avoid*
is pointer for an unspecified type, and avoid**
is a pointer to a pointer for an unspecified type.void
是一种没有对象的类型。void *
是传统的标量类型。void **
也是一种传统的标量类型,恰好指向void *
。void *
可以用来指向任何东西,但我更喜欢只将它用于未初始化的存储。通常有更好的替代方法来将void *
指向实际对象。void
is a type which has no objects.void *
is a conventional scalar type.void **
is also a conventional scalar type that happens to point tovoid *
.void *
can be used to point to anything, but I prefer to use it only for uninitialized storage. There is usually a better alternative to pointing avoid *
at an actual object.