#include <iostream>
#include <cstdlib>
using namespace std;
class A
{
public:
A(int arg = 5)
{
cout<<"call A constructor"<<endl;
a = arg;
}
~A()
{
cout<<"call A destructor"<<endl;
}
void* operator new(size_t size)
{
cout<<"call A::operator new"<<endl;
return malloc(size);
}
void operator delete(void *ptr)
{
cout<<"call A::operator delete"<<endl;
free(ptr);
}
void* operator new(size_t size, void *pMem)
{
cout << "call A::placement new" << endl;
return (static_cast<int *>(pMem)) + 1;
}
void operator delete(void *ptr, void *pMem)
{
::operator delete(ptr, pMem);
}
void print_data()
{
cout << a << endl << b << endl;
}
private:
int a;
int b;
};
int main()
{
A *pa = new A;
pa->print_data();
new(pa) A(6);
pa->print_data();
delete pa;
return 0;
}
程序输出结果:
call A::operator new
call A constructor
5
0
call A::placement new
call A constructor
5
6
call A destructor
call A::operator delete
由程序执行结果可知,代码
new(pa) A(6);
先调用
operator new(size_t size, void *pMem)
然后调用构造函数,构造函数构造时传入的this指针地址为operator new的返回值,构造函数中a = arg 即this ->a = arg,a的地址由this指针地址加上对应的偏移算出,这才导致最终a = 5并未赋值,而b在构造函数中被赋值为6。所以,一般来说,placement new的返回值应为传入的指针。