我刚刚阅读了 new operator explanation on the 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;
}
我的问题是:
- 使用的最佳做法是什么 新运营商?
myclass* p3 = new myclass
是否等同于myclass* p3 = new myclass()
?
最佳答案
因为他们的目的不同。如果您不希望 new
在失败时抛出 std::bad_alloc
,您可以使用 nothrow
。如果你想在现有存储中分配你的对象,你可以使用 placement new ……如果你想要原始的、未初始化的内存,你可以直接调用 operator new
并将结果转换为目标类型。
在 99% 的情况下,new
的简单标准用法是 MyClass* c = new MyClass()
;
关于您的第二个问题:new Object()
与 new Object
形式通常并不相等。参见 this question and the responses了解详情。但那真的是吹毛求疵。通常它们是等价的,但为了安全起见,总是选择 new Object()
;请注意,在这个特定示例中,它们是相等的,因为 MyClass
没有任何成员,所以严格来说您的问题的答案是肯定的。
关于c++ - 为什么在 C++ 中有这么多不同的方法来使用 new 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5995664/