"new" 和有什么不一样?和“malloc"和“calloc"在 C++ 中?

2021-12-24 00:00:00 memory-management malloc c++ heap-memory

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?

推荐答案

newdelete 是 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 释放.
  • callocmalloc 类似,但使用常量 (0) 初始化分配的内存.需要用 free 释放.
  • new 通过调用构造函数(如果它是一个对象)来初始化分配的内存.用 new 分配的内存应该用 delete 释放(它依次调用析构函数).它不需要您手动指定所需的大小并将其转换为适当的类型.因此,它更现代,更不容易出错.
  • malloc allocates uninitialized memory. The allocated memory has to be released with free.
  • calloc is like malloc but initializes the allocated memory with a constant (0). It needs to be freed with free.
  • new initializes the allocated memory by calling the constructor (if it's an object). Memory allocated with new should be released with delete (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.

相关文章