为什么 C++ 需要对 malloc() 进行强制转换,而 C 不需要?
我一直对此很好奇 - 为什么在 C++ 中我必须从 malloc
转换返回值,而不是在 C 中?
I have always been curious about this - why do in C++ I have to cast return value from malloc
but not in C?
以下是 C++ 中有效的示例:
Here is the example in C++ that works:
int *int_ptr = (int *)malloc(sizeof(int*));
这是 C++ 中不起作用的示例(无强制转换):
And here is the example in C++ that doesn't work (no cast):
int *int_ptr = malloc(sizeof(int*));
我听说在 C 中,实际上,从 malloc()
转换输出是一个错误.
I heard that in C, in fact, casting an output from malloc()
is a mistake.
有人可以评论这个话题吗?
Can anyone comment on this topic?
推荐答案
几点:
C 允许将 void 指针隐式转换为任何其他对象指针类型.C++ 没有.
C allows void pointers to be implicitly converted to any other object pointer type. C++ does not.
在 C 中转换 malloc()
的结果将抑制有用的诊断,如果您忘记包含 stdlib.h 或没有 malloc()
在范围内.请记住,如果 C 看到一个没有事先声明的函数调用,它将假定该函数返回 int
.如果您没有对 malloc()
的声明并且不进行强制转换,您将得到一个诊断结果,表明您正在尝试分配不兼容的类型(int 到指针).如果您转换结果,则会抑制诊断,并且可能会出现运行时问题,因为不能保证将指针值转换为 int 并再次转换回指针会给您一个有用的结果.
Casting the result of malloc()
in C will supress a useful diagnostic if you forget to include stdlib.h or otherwise don't have a declaration for malloc()
in scope. Remember that if C sees a function call without a prior declaration, it will assume that the function returns int
. If you don't have a declaration for malloc()
and you leave off the cast, you'll get a diagnostic to the effect that you're trying to assign incompatible types (int to pointer). If you cast the result, you supress the diagnostic and will potentially have runtime issues, since it's not guaranteed that converting a pointer value to an int and back to a pointer again will give you a useful result.
如果你在写 C++,你应该使用 new
和 delete
而不是 malloc()
和 free()代码>.是的,是的,是的,我听说过人们希望他们的代码同时编译为 C 和 C++ 的所有原因,但是为该语言使用正确的内存管理工具的好处超过了维护两个版本 IMO 的成本.
If you're writing C++, you should be using new
and delete
instead of malloc()
and free()
. Yeah, yeah, yeah, I've heard all the reasons why people want their code to compile as both C and C++, but the benefits of using the right memory management tool for the language outweigh the cost of maintaining two versions IMO.
注意:void *
类型是在C89标准中添加的;早期版本的 C 有 malloc()
返回 char *
,因此在这些版本中,如果您将结果分配给不同的结果,则需要 指针类型.不过,几乎每个人都至少支持 C89 标准,因此您遇到这些旧实现之一的几率非常非常低.
Note: the void *
type was added in the C89 standard; earlier versions of C had malloc()
return char *
, so in those versions the cast was required if you were assigning the result to a different pointer type. Almost everybody supports at least the C89 standard though, so the odds of you running into one of those older implementations is very, very low.
相关文章