fork download
  1. #include <iostream>
  2. #include <new>
  3. #include <cstdlib>
  4.  
  5. using namespace std;
  6.  
  7. struct Test
  8. {
  9. Test(int d) : data(d) { cerr << "Test::Test" << endl; }
  10. ~Test() { cerr << "Test::~Test" << endl; }
  11.  
  12. /* static */ void* operator new(size_t sz, int d);
  13. /* static */ void operator delete(void* p) noexcept;
  14. int data;
  15. };
  16.  
  17. // global new and delete
  18. void* operator new(size_t sz)
  19. {
  20. cerr << "::new" << endl;
  21. return malloc(sz);
  22. }
  23. void operator delete(void* p) noexcept
  24. {
  25. cerr << "::delete" << endl;
  26. free(p);
  27. }
  28.  
  29. void* operator new(size_t sz, int d)
  30. {
  31. cerr << "::new, data:" << d << endl;
  32. return malloc(sz);
  33. }
  34. void operator delete(void* p, int d) noexcept
  35. {
  36. cerr << "::delete, data:" << d << endl;
  37. free(p);
  38. }
  39.  
  40. // member new and delete
  41. void* Test::operator new(size_t sz, int d)
  42. {
  43. cerr << "Test::new, data:" << d << endl;
  44. return ::operator new(sz, d);
  45. }
  46. void Test::operator delete(void* p) noexcept
  47. {
  48. Test* t = reinterpret_cast<Test*>(p);
  49. cerr << "Test::delete, data:" << t->data << endl;
  50. ::operator delete(p, t->data);
  51. }
  52.  
  53. int main()
  54. {
  55. int x;
  56. while (cin >> x)
  57. {
  58. Test *t = new(x) Test(x);
  59. /* ... */
  60. delete t;
  61. }
  62. return 0;
  63. }
  64.  
Success #stdin #stdout #stderr 0s 4524KB
stdin
42
10
6
quit
stdout
Standard output is empty
stderr
Test::new, data:42
::new, data:42
Test::Test
Test::~Test
Test::delete, data:42
::delete, 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