fork download
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <new>
  4.  
  5. using namespace std;
  6.  
  7. struct A
  8. {
  9. static void * operator new [] (size_t t, int first, int second);
  10. static void operator delete [] (void *p, size_t t);
  11. static void operator delete [] (void *p, int first, int second)
  12. {
  13. cout << "3 parameters deallocation: " << first << ", " << second << endl;
  14. return ::operator delete[](p);
  15. }
  16. };
  17.  
  18. // simple POD struct to store the placement parameters
  19. struct info {
  20. int first_param, second_param;
  21. };
  22.  
  23. void* A::operator new [] (size_t t, int first, int second)
  24. {
  25. cout << "3 parameters allocation: " << first << ", " << second << endl;
  26. // allocate sizeof(info) extra space to store the parameters
  27. auto const p = ::operator new[](t + sizeof(info));
  28. auto const pinfo = reinterpret_cast<char*>(p) + t;
  29. auto const tmp = info{first, second};
  30. std::copy_n(reinterpret_cast<const char*>(&tmp), sizeof(info), pinfo);
  31. return p;
  32. }
  33.  
  34. static void A::operator delete [] (void *p, std::size_t t) {
  35. // retrieve the parameters that we stored in operator new [].
  36. auto const pinfo = reinterpret_cast<const char*>(p) + t;
  37. auto tmp = info{};
  38. std::copy_n(pinfo, sizeof(info), reinterpret_cast<char*>(&tmp));
  39. cout << "Deleting with original parameters: " << tmp.first_param << ", " << tmp.second_param << endl;
  40. ::operator delete[](p);
  41. }
  42.  
  43. int main()
  44. {
  45. A *a = new (5,5) A[10]; //operator new [] (size_t, int, int) invoked
  46. A *b = new (3,7) A[2]; //operator new [] (size_t, int, int) invoked
  47. delete [] a;
  48. delete [] b;
  49. }
  50.  
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
3 parameters allocation: 5, 5
3 parameters allocation: 3, 7
Deleting with original parameters: 5, 5
Deleting with original parameters: 3, 7