创建没有"new"运算符的类的新实例

Sam*_*Sam 20 c++ class

只是一个简单的问题.正如标题所示,我只使用"new"运算符来创建类的新实例,所以我想知道其他方法是什么以及如何正确使用它.

Naw*_*waz 30

您也可以使用不使用的类的自动实例new,如:

class A{};

//automatic 
A a;             

//using new
A *pA = new A();

//using malloc and placement-new
A *pA = (A*)malloc(sizeof(A));
pA = new (pA) A();

//using ONLY placement-new
char memory[sizeof(A)];
A *pA = new (memory) A();
Run Code Online (Sandbox Code Playgroud)

最后两个使用位置,新的是从稍稍不同的新的.placement-new用于通过调用构造函数来构造对象.在第三个例子中,malloc只分配内存,它不调用构造函数,这就是使用placement-new来调用构造函数来构造对象的原因.

另请注意如何删除内存.

  //when pA is created using new
  delete pA;

  //when pA is allocated memory using malloc, and constructed using placement-new
  pA->~A(); //call the destructor first
  free(pA); //then free the memory

  //when pA constructed using placement-new, and no malloc or new!
  pA->~A(); //just call the destructor, that's it!
Run Code Online (Sandbox Code Playgroud)

要了解什么是新的展示位置,请阅读以下常见问题解答:

  • 此外,要了解使用自动实例的优点,您需要了解[RAII](http://stackoverflow.com/questions/712639/). (3认同)
  • +1:我想知道*没有动态分配*的正确术语是什么.*自动* - 谢谢! (2认同)

Bjö*_*lex 5

你可以声明一个普通变量:

YourClass foo;
Run Code Online (Sandbox Code Playgroud)

  • 假设它有一个默认构造函数。 (2认同)