c库中malloc的转换结果

Cast result of malloc in c library

我正在查看 Do I cast the result of malloc?,您似乎不应该将结果转换为纯 C 代码,因为它可能隐藏错误并且是多余的。但我也看到有人说 c++ 需要强制转换,所以所有 c 库都应该强制转换 malloc 的结果,因为它们实际上可以用在 c++ 项目中吗?

没有。如果它是 C 代码,它应该被编译为 C,而不是 C++,因此编译器将允许从 void* 到其他指针的隐式转换。

只有在 C++ 代码中使用 malloc 时才需要转换它 - 在我看来它是 "bad smell" - 换句话说,这是代码应该现代化的标志使用 newvector 或类似的东西。 (当然,这样做是有正当理由的——例如,你可能有大约 10k 行有用的代码,你需要将这些代码深入到 C++ 框架中来做其他事情——但通常,最好的方法是编写一些 C++绑定到那些 10k 行并继续将其编译为 C)

it appears that you should not cast the result in pure c code because it's potentially hides bugs and is redundant

没错。

shouldn't all c libraries cast the result of malloc because they could realistically be used in a c++ project?

没有。 C 库可以在 C++ 项目中使用,但仍然可以编译为 C。