/* We generally refer to placement new as overloading new() delete() We can overload class member operator new(), provided that each version of the declaration has a unique parameter list, The first parameter is size_t, and the rest of the parameters are initialized with the placement arguments specified by new. foo* p = new(300,'c')foo; */ #include <iostream> #include <cstdlib> using namespace std; class Bad{ public: Bad(){ cout<<"Allocated memory successfully!"<<endl; } } ; class foo{ public: foo(){cout<<"foo::foo()"<<endl; } foo(int ){cout<<"foo::foo(int)"<<endl;throw Bad();//Throw expcetion here, test placement operator delete If it can throw an error, it means that the memory has been called . } //(1) Overload of general operator new() void* operator new(size_t size){ return malloc(size); } //(2) This is the overloaded form of placement new() already provided by the standard library void * operator new(size_t size,void*start){ return start; } //(3) This is a new placement new void * operator new(size_t size,long extra){ return malloc(size+extra); } //(4) This is another placement new void * operator new(size_t size,long extra,char init){ return malloc(size+extra); } //(5) This is another placement new but deliberately mistyped the type of the first parameter (must be size_t to conform to normal operator new) /* void* operator new(long extra,char init){ return malloc(extra); } */ //We wrote 5 placement new above, then we should write 5 placement delete, but even if operator delete() cannot correspond to operator new one by one, there will be no error, which means giving up processing any abnormal. }; int main(){ foo str; foo* p1 = new foo; foo* p2 = new(&str)foo; foo* p3 = new(100)foo; foo* p4 = new (100,'a')foo; foo* p5 = new(100)foo(1); return 0; }