定位new
常规的new是分配内存,然后调用相应的构造函数,而定位new是在已经分配内存的上面调用构造函数:
// ConsoleApplication7.cpp : 定义控制台应用程序的入口点。 #include "stdafx.h" #include<iostream> using namespace std; class A { public: A() { cout << "A()被调用了" << endl; } ~A() { cout << "~A()被调用了" << endl; } private: int x; int y; }; int main() { void* p = (void*)new char[sizeof(A)]; A* s = new(p) A(); s->~A(); delete (void*)p; return 0; }