铸字的malloc C ++ [英] Typecasting malloc C++

查看:83
本文介绍了铸字的malloc C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些C code。与它的malloc语句,我想用一些C ++ code合并。

我在想,什么时候,为什么被强制转换在C的malloc neccessary ++?

通话

例如:

 的char *海峡=(字符*)malloc的(strlen的(的argv [1])* sizeof的(炭));


解决方案

  

时间和原因是类型转换在C ++中对malloc neccessary打个电话?


时总是不分配给一个无效* ,因为无效* 不会隐式转换为其他类型的指针,一路上它在C.但真正的答案是您不应该永远使用的malloc 在C ++ 在首位。


我并不是建议你应该使用而不是的malloc 。现代C ++ code应该使用谨慎,或者完全如果可能避免。你应该隐藏所有使用或使用非基本类型(如的std ::矢量按XEO提及)。我不是真的有资格给在这个方向的建议,由于我有限的经验,但的这篇文章搜索C ++避免新的沿应该有所帮助。然后你会想看看:

I have some C code with malloc statements in it that I want to merge with some C++ code.

I was wondering when and why is typecasting a call to malloc neccessary in C++?

For example:

char *str = (char*)malloc(strlen(argv[1]) * sizeof(char));

解决方案

when and why is typecasting a call to malloc neccessary in C++?

Always when not assigning to a void *, since void * doesn't convert implicitly to other pointer types, the way it does in C. But the true answer is you shouldn't ever use malloc in C++ in the first place.


I am not suggesting you should use new instead of malloc. Modern C++ code should use new sparingly, or avoid it altogether if possible. You should hide all use of new or use non-primitive types (like std::vector mentioned by Xeo). I'm not really qualified to give advice in this direction due to my limited experience but this article along with searching for "C++ avoid new" should help. Then you'll want to look into:

这篇关于铸字的malloc C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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