#include <iostream>
#include <new>
#include <cstdlib>
using namespace std;
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;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8bmV3PgojaW5jbHVkZSA8Y3N0ZGxpYj4KCnVzaW5nIG5hbWVzcGFjZSBzdGQ7CgpzdHJ1Y3QgVGVzdAp7CiAgVGVzdChpbnQgZCkgOiBkYXRhKGQpIHsgY2VyciA8PCAiVGVzdDo6VGVzdCIgIDw8IGVuZGw7IH0KICB+VGVzdCgpICAgICAgICAgICAgICAgeyBjZXJyIDw8ICJUZXN0Ojp+VGVzdCIgPDwgZW5kbDsgfQoKICAvKiBzdGF0aWMgKi8gdm9pZCogb3BlcmF0b3IgbmV3KHNpemVfdCBzeiwgaW50IGQpOwogIC8qIHN0YXRpYyAqLyB2b2lkICBvcGVyYXRvciBkZWxldGUodm9pZCogcCkgbm9leGNlcHQ7CiAgaW50IGRhdGE7Cn07CgovLyBnbG9iYWwgbmV3IGFuZCBkZWxldGUKdm9pZCogb3BlcmF0b3IgbmV3KHNpemVfdCBzeikKewogIGNlcnIg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ete, data:42
Test::new, data:10
::new, data:10
Test::Test
Test::~Test
Test::delete, data:10
::delete, data:10
Test::new, data:6
::new, data:6
Test::Test
Test::~Test
Test::delete, data:6
::delete, data:6