为什么有这么多不同的方法在C++中使用new运算符

xia*_*o 啸 8 c++ pointers new-operator

我刚刚在cplusplus.com上阅读了新的操作员说明.该页面给出了一个示例,演示了使用new运算符的四种不同方法:

// operator new example
#include <iostream>
#include <new>
using namespace std;

struct myclass {myclass() {cout <<"myclass constructed\n";}};

int main () {

   int * p1 = new int;
// same as:
// int * p1 = (int*) operator new (sizeof(int));

   int * p2 = new (nothrow) int;
// same as:
// int * p2 = (int*) operator new (sizeof(int),nothrow);

   myclass * p3 = (myclass*) operator new (sizeof(myclass));
// (!) not the same as:
// myclass * p3 = new myclass;
// (constructor not called by function call, even for non-POD types)

   new (p3) myclass;   // calls constructor
// same as:
// operator new (sizeof(myclass),p3)

   return 0;
}
Run Code Online (Sandbox Code Playgroud)

我的问题是:

  1. 使用new运算符的最佳做法是什么?
  2. myclass* p3 = new myclass相当于myclass* p3 = new myclass()

Ale*_*ler 6

因为他们有不同的目的.如果你不想newstd::bad_alloc失败,你可以使用nothrow.如果你想在现有存储中分配对象,你可以使用placement new ...如果你想要原始的,未初始化的内存,你可以operator new直接调用并将结果转换为目标类型.

new所有案例中99%的普通标准用法是MyClass* c = new MyClass();

对于你的第二个问题:new Object()对比new Object表格通常不相同.有关详细信息,请参阅此问题和回复.但这真的是挑剔.通常它们是等价的,但为了安全起见总是挑选new Object(); 请注意,在这个特定的样本中它们是相同的,因为MyClass没有任何成员,所以严格来说,你的问题的答案是肯定的.

  • 不,它是`MyClass c;` (3认同)