类型转换 malloc C++ [英] Typecasting malloc C++

查看:30
本文介绍了类型转换 malloc 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:

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

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