什么是C ++中的void指针? [英] What is a void pointer in C++?
问题描述
我经常看到类似下面的代码:
I often see code which resembles something like the following:
void * foo int bar);
这是什么意思?这是否意味着它可以返回任何 ?这类似于C#中的动态
或对象
吗?
What does this mean? Does it mean that it can return anything? Is this similar to dynamic
or object
in C#?
推荐答案
A void *
并不意味着什么。它是一个指针,但它指向的类型是未知的。
A void*
does not mean anything. It is a pointer, but the type that it points to is not known.
这不是它可以返回任何东西。返回 void *
的函数通常执行以下操作之一:
It's not that it can return "anything". A function that returns a void*
generally is doing one of the following:
- 它正在处理未格式化的内存。这是
operator new
和malloc
返回:指向一定大小的内存块的指针。因为内存没有类型(因为它还没有一个正确构造的对象),它是无类型的。 IE:void
。 - 这是一个不透明的句柄;它引用创建的对象而不命名特定类型。这样做的代码通常形式不好,因为这最好通过向前声明一个结构/类,而不是为它提供一个公共定义。
- 它有明确的文档告诉你可以使用指针的类型。
- It is dealing in unformatted memory. This is what
operator new
andmalloc
return: a pointer to a block of memory of a certain size. Since the memory does not have a type (because it does not have a properly constructed object in it yet), it is typeless. IE:void
. - It is an opaque handle; it references a created object without naming a specific type. Code that does this is generally poorly formed, since this is better done by forward declaring a struct/class and simply not providing a public definition for it. Because then, at least it has a real type.
- It has explicit documentation telling you what type(s) that you can use the pointer for.
不是动态
或物件
在C#。这些结构实际上知道什么是原始类型; void *
不会。这使得它比任何那些更危险,因为它很容易弄错。
It is nothing like dynamic
or object
in C#. Those constructs actually know what the original type is; void*
does not. This makes it far more dangerous than any of those, because it is very easy to get it wrong.
在个人注意,如果你看到使用 void *
的often,你应该重新思考你正在看什么代码。 void *
用法,特别是C ++中的,应该是罕见的,用于处理原始内存。
And on a personal note, if you see code that uses void*
's "often", you should rethink what code you're looking at. void*
usage, especially in C++, should be rare, used primary for dealing in raw memory.
这篇关于什么是C ++中的void指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!