话不多说,直接上代码。
#include <iostream>
#include <cstdlib>
using namespace std;
struct Test //定义结构体
{
int num;
// int num2;
Test()
{
// cout<< "Test()" <<endl;
}//析构函数
~Test()
{
// cout<< "~Test()" <<endl;
}//析构函数
void* operator new[] (size_t size)
{
cout << "operator new[]: " << size << endl;
return malloc(size);
}
void operator delete[] (void* p)
{
cout << "operator delete[]: " << p << endl;
free(p);
}
};
int main()
{
Test* test = new Test[5]; //创建长度为5的数组
delete [] test;
}
运行结果:
此处 ,本意想要申请的类数组大小为4*5=20个字节,但是实际上却得到了28个字节,这是为什么呢?
原来定义了析构函数的类operator new[] (size_t size)的参数size会额外加一个long int大小来存储数组大小信息供析构函数使用,因为我当前系统为64位,故这个存储数组大小的变量为64位即8个字节,故得到的指针往前推得两个int组成的long int即为数组大小,代码如下:
#include <iostream>
#include <cstdlib>
using namespace std;
struct Test //定义结构体
{
int num;
// int num2;
Test()
{
// cout<< "Test()" <<endl;
}//析构函数
~Test()
{
// cout<< "~Test()" <<endl;
}//析构函数
void* operator new[] (size_t size)
{
cout << "operator new[]: " << size << endl;
return malloc(size);
}
void operator delete[] (void* p)
{
cout << "operator delete[]: " << p << endl;
free(p);
}
};
int main()
{
Test* test = new Test[5]; //创建长度为5的数组
cout <<"sizeof(int):" <<sizeof(int) <<endl;
cout << "sizeof(Test):"<<sizeof(Test) <<endl;
// test[0].num = 88;
// test[1].num = 77;
// test[2].num = 66;
// test[3].num = 55;
// test[4].num = 44;
// cout << (*((int*)test+4)) <<endl;
// cout << (*((int*)test+3)) <<endl;
// cout << (*((int*)test+2)) <<endl;
// cout << (*((int*)test+1)) <<endl;
// cout << (*((int*)test)) <<endl;
// cout << (*((int*)test-1)) <<endl;
// cout << (*((int*)test-2)) <<endl;
long int arraysize = (long)(*((int*)test-1)) << 32 | (*((int*)test-2)) & 0xFFFFFFFFL;
cout<<"test size:"<<arraysize<<endl;
delete [] test;
}
运行结果如下:
我的系统大小端测试:
#include <stdio.h>
// 共用体中很重要的一点:a和b都是从u1的低地址开始存放的。
// 假设u1所在的4字节地址分别是:0、1、2、3的话,那么a自然就是0、1、2、3;
// b所在的地址是0而不是3.
union myunion
{
int a;
char b;
};
// 如果是小端模式则返回1,小端模式则返回0
int is_little_endian(void)
{
union myunion u1;
u1.a = 0x12345678; // 地址0的那个字节内是0x78(小端)或者0x12(大端)
if(0x78 == u1.b)
return 1;
else if(0x12 == u1.b)
return 0;
}
int is_little_endian2(void)
{
int a = 0x12345678;
char b = *((char *)(&a)); // 指针方式其实就是共用体的本质
if(0x78 == b)
return 1;
else if(0x12 == b)
return 0;
}
int main(void)
{
int i = is_little_endian2();
//int i = is_little_endian();
if (i == 1)
{
printf("小端模式\n");
}
else
{
printf("大端模式\n");
}
return 0;
}
结果出来我的系统是小端,所以long int c = (long)(高地址数据) << 32 | (低地址数据) & 0xFFFFFFFFL;