为什么C ++需要的malloc铸造(),但C没有? [英] Why does C++ require a cast for malloc() but C doesn't?

查看:141
本文介绍了为什么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()是一个错误。

能在这个话题的人对此有何评论?

Can anyone comment on this topic?

推荐答案

几点:

C允许空指针隐式转换为任何其他对象的指针类型。 C ++不。

C allows void pointers to be implicitly converted to any other object pointer type. C++ does not.

铸造)的结果的malloc(用C将苏preSS一个有用的诊断,如果你忘了包括stdlib.h中或以其他方式不具备的声明为范围的malloc()。请记住,如果C看到一个函数调用没有事先声明,它会假设该函数返回 INT 。如果你没有为的malloc的声明(),你离开了剧组,你会得到一个诊断到你想分配不兼容的类型的影响(INT为指针)。如果你投的结果,你苏preSS的诊断及将可能具有运行时问题,因为它不能保证指针值转换为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 ++,你应该使用删除而不是的malloc()免费()。是啊,是啊,是啊,我听说过,为什么人们希望自己的code编译的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.

注:无效* 在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.

这篇关于为什么C ++需要的malloc铸造(),但C没有?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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