struct Test
{
Test(int d) : data(d) { cerr << "Test::Test" << endl; }
~Test() { cerr << "Test::~Test" << endl; }
/* static */ void* operator new(size_t sz, int d);
/* static */ void operator delete(void* p) noexcept;
int data;
};
// global new and delete
void* operator new(size_t sz)
{
cerr << "::new" << endl;
return malloc(sz);
}
void operator delete(void* p) noexcept
{
cerr << "::delete" << endl;
free(p);
}
void* operator new(size_t sz, int d)
{
cerr << "::new, data:" << d << endl;
return malloc(sz);
}
void operator delete(void* p, int d) noexcept
{
cerr << "::delete, data:" << d << endl;
free(p);
}
// member new and delete
void* Test::operator new(size_t sz, int d)
{
cerr << "Test::new, data:" << d << endl;
return ::operator new(sz, d);
}
void Test::operator delete(void* p) noexcept
{
Test* t = reinterpret_cast<Test*>(p);
cerr << "Test::delete, data:" << t->data << endl;
::operator delete(p, t->data);
}
int main()
{
int x;
while (cin >> x)
{
Test *t = new(x) Test(x);
/* ... */
delete t;
}
return 0;
}