我测试了这段代码,只是想找出 C++ 实际为 new 运算符保留了多少内存。
#include<iostream>
using namespace std;
int main() {
cout << "alignment of " << alignof(int) << endl;
int *intP1 = new int;
*intP1 = 100;
cout << "address of intP1 " << intP1 << endl;
int *intP2 = new int;
*intP2 = 999;
cout << "address of intP2 " << intP2 << endl;
int *intP3 = new int;
cout << "address of intP3 " << intP3 << endl;
*intP3 = 333;
cout << endl;
cout << (reinterpret_cast<char *>(intP3)-reinterpret_cast<char *>(intP2)) << endl;
cout << intP3-intP2 << endl;
cout << endl;
cout << *(intP1) << endl;
cout << *(intP1+4) << endl;
cout << *(intP1+8) << endl;
cout << *(intP1+16) << endl;
delete intP1;
delete intP2;
delete intP3;
return 0;
}
在使用 -std=c++11 标志编译代码并运行它之后,这是我从 x86_64 机器上得到的。
alignment of int4
address of intP1 = 0xa59010
address of intP2 = 0xa59030
address of intP3 = 0xa59050
the distance of intP3 and intP2 = 32
intP1 value = 100
is this a padding value = 0
intP2 value = 999
intP3 value = 333
似乎在使用 new 为整数分配 4 字节内存时,它实际上保留了 32 字节块,即 8 个整数的总空间。根据c++对齐的解释,对于64位机器,内存是按16字节对齐的,为什么这里的距离是32字节呢?
有人可以帮我解决这个问题吗?提前致谢。