new 在C++ 中的用法

我对C++一无所知

看参考手册##


来看一下参考手册,总共有三种用法
下面是网站上给出的例子

// operator new example
#include <iostream>     // std::cout
#include <new>          // ::operator new

struct MyClass {
  int data[100];
  MyClass() {std::cout << "constructed [" << this << "]
";}
};

int main () {

  std::cout << "1: ";
  MyClass * p1 = new MyClass;
      // allocates memory by calling: operator new (sizeof(MyClass))
      // and then constructs an object at the newly allocated space
      // 分配内存空间使用制定的大小,然后使用恰当的初始化函数初始化,注意其实这种分配空间等价与  ::operator new (sizeof(MyClass))  也就是operator 之分配空间并不调用
      //

  std::cout << "2: ";
  MyClass * p2 = new (std::nothrow) MyClass;
      // allocates memory by calling: operator new (sizeof(MyClass),std::nothrow)
      // and then constructs an object at the newly allocated space
      // 这种方式遇到错的时候会返回nullptr 而不是想(1) 一样throw exception

  std::cout << "3: ";
  new (p2) MyClass;
      // does not allocate memory -- calls: operator new (sizeof(MyClass),p2)
      // but constructs an object at p2
      //  第三中方式,啥也不干返回p2 ,如果按照new 的语法进行就是  the proper initialization will be performed.

  // Notice though that calling this function directly does not construct an object:
  std::cout << "4: ";
  MyClass * p3 = (MyClass*) ::operator new (sizeof(MyClass));
      // allocates memory by calling: operator new (sizeof(MyClass))
      // but does not call MyClass's constructor
      // 最后一种简单粗暴之分配空间而不进行初始化操作
  delete p1;
  delete p2;
  delete p3;

  return 0;
}
原文地址:https://www.cnblogs.com/sfzyk/p/8576166.html