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

标签 c++ pointers new-operator

我刚刚阅读了 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;
}

我的问题是:

  1. 使用的最佳做法是什么 新运营商?
  2. 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/

相关文章:

c++ - 实例化和特化的定义相互依赖

c++ - 以这种方式初始化的 char 数组是否自动添加了空终止符?

c++ - Lambda 捕获 C++14

c++ - 如何在不打开新窗体的情况下更改 Window 或 QWidget?

c - 指针和内存地址

c++ - 哪一种是在 C++ 中分配未初始化内存的最惯用的方法

c# - C#/.Net 中 'new' 属性的优缺点?

c++ - 新的运营商 ->有或没有

c++ - 有没有办法安全地指向函数内部声明的临时值?

c - 在c中生成字指针数组