类型转换 malloc C++

2021-12-31 00:00:00 c malloc casting c++

我有一些带有 malloc 语句的 C 代码,我想与一些 C++ 代码合并.

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

我想知道何时以及为什么需要在 C++ 中对 malloc 调用进行类型转换?

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

例如:

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

推荐答案

何时以及为什么需要在 C++ 中对 malloc 调用进行类型转换?

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

总是在不分配给 void * 时,因为 void * 不会像在 C 中那样隐式转换为其他指针类型.但真正的答案首先,您不应该在 C++ 中使用 malloc.

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.

我不是建议您应该使用 new 而不是 malloc.现代 C++ 代码应该谨慎使用 new,或者尽可能避免使用它.您应该隐藏所有对 new 的使用或使用非原始类型(如 Xeo 提到的 std::vector).由于我的经验有限,我真的没有资格在这方面提供建议,但是 这篇文章 以及搜索C++ 避免新的"应该会有所帮助.然后你会想看看:

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:

  • std::alocator
  • 智能指针

相关文章