Typecasting malloc C++(类型转换 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:
- std::alocator
- 智能指针
这篇关于类型转换 malloc C++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:类型转换 malloc C++
基础教程推荐
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
