#include<iostream>
#include<cstdlib>
using std::cout;
using std::endl;
using std::hex;
class X
{
public:
X(int q =0): a(q){}
~X(){ cout <<"del"<< endl;}
private:
int a;
};
/**< 重载operator new[]函数,new操作符会首先调用该函数 */
void*operatornew[](size_t size)
{
void*p = malloc(size);
cout <<"new[]:"<< size << endl;// 实际所分内存大小
cout <<"new[]:"<< hex << p << endl;// 实际所分内存起始位置
return p;
}
int main()
{
X *q =new X[5];// 所需内存大小:5 * 4 = 20Byte
cout << hex << q << endl;
/**< 将q所指地址向前移动4Byte(p是int型指针),取出数组长度 */
cout <<*(reinterpret_cast<int*>(q)-1)<< endl;
delete[] q;
return0;
}
结果: