c++ - 为什么会有两个版本的 operator new 重载?

标签 c++ new-operator c++14 iso

new 单独重载的原因是什么?和 new[]名为 operator newoperator new[] ?由于它们都仅用于分配一定数量的内存 - 为什么我要为它们中的每一个编写不同的代码?

最佳答案

new 用于创建单个对象

int * foo = new int;  // now I have one int*

new[]用于创建多个对象并将它们放入连续的内存(数组)

int * bar = new int[someIntegerValue];

使用 new 时,您需要确保将其与正确的 delete 调用相匹配。如果您使用 new,则需要相应调用 deletenew[]delete[]< 也是如此

int * foo = new int;  // now I have one int*
//more code...
// now that I'm done with foo
delete foo;

int * bar = new int[someIntegerValue];
//more code...
// now that I'm done with bar.
delete [] bar;

关于c++ - 为什么会有两个版本的 operator new 重载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29413038/

相关文章:

c++ - 即使清理后内存也没有减少

c++ - 寻找一种模式来避免在虚函数的实现中使用 dynamic_cast

c++ - 在几层抽象之后尝试交换指针 vector 中的指针

c++ - 实际上什么返回类型有一个新的?

c++ - 全局新运算符调用语法

c++ - 将不可复制的闭包对象传递给 std::function 参数

c++ - Qt QScrollArea 自动滚动

c++ - 新建/删除[] 和 VirtualAlloc

c++ - 如何让数字停止使用 std::wfstream 库中的分组分隔符?

c++ - 在 visual studio 2015 cmake 中启用 c++14