为 new
单独重载的原因是什么?和 new[]
名为 operator new
和 operator new[]
?由于它们都仅用于分配一定数量的内存 - 为什么我要为它们中的每一个编写不同的代码?
最佳答案
new
用于创建单个对象
int * foo = new int; // now I have one int*
new[]
用于创建多个对象并将它们放入连续的内存(数组)
int * bar = new int[someIntegerValue];
使用 new 时,您需要确保将其与正确的 delete
调用相匹配。如果您使用 new
,则需要相应调用 delete
,new[]
和 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/