new[] 到底做了什么?

时间:2023-03-09 04:27:10
new[] 到底做了什么?
  1. #include<iostream>
  2. #include<cstdlib>
  3. using std::cout;
  4. using std::endl;
  5. using std::hex;
  6. class X
  7. {
  8. public:
  9. X(int q =0): a(q){}
  10. ~X(){ cout <<"del"<< endl;}
  11. private:
  12. int a;
  13. };
  14. /**< 重载operator new[]函数,new操作符会首先调用该函数 */
  15. void*operatornew[](size_t size)
  16. {
  17. void*p = malloc(size);
  18. cout <<"new[]:"<< size << endl;// 实际所分内存大小
  19. cout <<"new[]:"<< hex << p << endl;// 实际所分内存起始位置
  20. return p;
  21. }
  22. int main()
  23. {
  24. X *q =new X[5];// 所需内存大小:5 * 4 = 20Byte
  25. cout << hex << q << endl;
  26. /**< 将q所指地址向前移动4Byte(p是int型指针),取出数组长度 */
  27. cout <<*(reinterpret_cast<int*>(q)-1)<< endl;
  28. delete[] q;
  29. return0;
  30. }

结果:
new[] 到底做了什么?