What is the difference between quot;newquot; and quot;mallocquot; and quot;callocquot; in C++?(new 和有什么不一样?和“malloc和“calloc在 C++ 中?)
问题描述
new"和new"有什么区别?和malloc"和calloc";和其他家庭成员?
What is the difference between "new" and "malloc" and "calloc" and others in family?
(何时)除了new"之外我还需要什么吗??
(When) Do I need anything other than "new" ?
其中一个是否使用其他实现?
Is one of them implemented using any other?
推荐答案
new 和 delete 是 C++ 特定的功能.它们在 C 中不存在. malloc 是老派的 C 做事方式.大多数情况下,您不需要在 C++ 中使用它.
new and delete are C++ specific features. They didn't exist in C. malloc is the old school C way to do things. Most of the time, you won't need to use it in C++.
malloc分配未初始化的内存.分配的内存必须用free释放.calloc与malloc类似,但使用常量 (0) 初始化分配的内存.需要用free释放.new通过调用构造函数(如果它是一个对象)来初始化分配的内存.用new分配的内存应该用delete释放(它依次调用析构函数).它不需要您手动指定所需的大小并将其转换为适当的类型.因此,它更现代,更不容易出错.
mallocallocates uninitialized memory. The allocated memory has to be released withfree.callocis likemallocbut initializes the allocated memory with a constant (0). It needs to be freed withfree.newinitializes the allocated memory by calling the constructor (if it's an object). Memory allocated withnewshould be released withdelete(which in turn calls the destructor). It does not need you to manually specify the size you need and cast it to the appropriate type. Thus, it's more modern and less prone to errors.
这篇关于"new" 和有什么不一样?和“malloc"和“calloc"在 C++ 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:"new" 和有什么不一样?和“malloc"和“calloc"在 C++ 中?
基础教程推荐
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 常量变量在标题中不起作用 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
