20

我试图了解 C 和 C++ 在 void 指针方面的区别。以下在 C 中编译,但不是在 C++ 中编译(所有编译都使用 gcc/g++ -ansi -pedantic -Wall 完成):

int* p = malloc(sizeof(int));

因为mallocreturn void*,C++ 不允许分配给它,int*而 C 确实允许。

但是,这里:

void foo(void* vptr)
{
}

int main()
{
    int* p = (int*) malloc(sizeof(int));
    foo(p);
    return 0;
}

C++ 和 C 都可以毫无怨言地编译它。为什么?

K&R2 说:

任何指向对象的指针都可以转换为类型void *而不会丢失信息。如果将结果转换回原始指针类型,则恢复原始指针。

这很好地总结了void*C 中的所有转换。C++ 标准规定了什么?

4

3 回答 3

38

在 C 中,指向和指向的指针转换void*始终是隐式的。

在 C++ 中,从T*to的转换void*是隐式的,但void*到其他任何东西都需要强制转换。

于 2009-11-15T07:01:22.953 回答
6

C++ 的类型比 C 更强。许多转换,特别是那些暗示对值的不同解释的转换,都需要显式转换。C++ 中的new运算符是一种类型安全的在堆上分配内存的方法,无需显式强制转换。

于 2009-11-15T07:04:04.093 回答
-1

It is useful to understand that pointer type conversions don't really require execution of extra CPU instructions. They are analysed during the compile time to understand the intensions of the developer. void * is an opaque pointer. All it says that the type of pointed object is unknown. C is weakly typed. It allows direct conversion between (void *) and any (T*) implicitly. C++ is strongly typed. A conversion from (void *) to (T*) wouldn't really make good case for a strongly typed language. But C++ had to stay backwards compatible with C, hence it had to allow such conversions. The guiding principle then is: explicit is better than implicit. Hence if you wish to convert an (void*) to some specific (T*) pointer, you need to explicitly write that in code. Conversion from (T*) 到 ( void*) 不需要显式转换,因为直接对 (void*) 指针无能为力(尽管可以调用 free())。因此 ( T*) 到 ( void*) 的转换非常安全。

于 2009-11-15T07:22:40.867 回答