只是一个简单的问题.正如标题所示,我只使用"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)
要了解什么是新的展示位置,请阅读以下常见问题解答: