铸字的malloc C ++ [英] Typecasting 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 ++避免新的沿应该有所帮助。然后你会想看看:
- 的std :: alocator
- 智能指针
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 *
, sincevoid *
doesn't convert implicitly to other pointer types, the way it does in C. But the true answer is you shouldn't ever usemalloc
in C++ in the first place.
I am not suggesting you should use
new
instead ofmalloc
. Modern C++ code should usenew
sparingly, or avoid it altogether if possible. You should hide all use ofnew
or use non-primitive types (likestd::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:
- std::alocator
- Smart pointers
这篇关于铸字的malloc C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!