大多数有经验的程序员都知道数据对齐对于程序的性能很重要。我见过一些程序员编写的程序分配了比他们需要的更大的缓冲区,并使用对齐的指针作为开始。我想知道我是否应该在我的程序中这样做,我不知道 C++ 的新操作返回的地址是否对齐有任何保证。于是我写了一个小程序来测试
for(size_t i = 0; i < 100; ++i) {
char *p = new char[123];
if(reinterpret_cast<size_t>(p) % 4) {
cout << "*";
system("pause");
}
cout << reinterpret_cast<void *>(p) << endl;
}
for(size_t i = 0; i < 100; ++i) {
short *p = new short[123];
if(reinterpret_cast<size_t>(p) % 4) {
cout << "*";
system("pause");
}
cout << reinterpret_cast<void *>(p) << endl;
}
for(size_t i = 0; i < 100; ++i) {
float *p = new float[123];
if(reinterpret_cast<size_t>(p) % 4) {
cout << "*";
system("pause");
}
cout << reinterpret_cast<void *>(p) << endl;
}
system("pause");
我使用的编译器是 Visual C++ Express 2008。看来新操作返回的所有地址都是对齐的。但我不确定。所以我的问题是:有任何保证吗?如果他们有保证,我不必调整自己,如果没有,我必须。
最佳答案
对齐具有来自标准 (3.7.3.1/2) 的以下保证:
The pointer returned shall be suitably aligned so that it can be converted to a pointer of any complete object type and then used to access the object or array in the storage allocated (until the storage is explicitly deallocated by a call to a corresponding deallocation function).
编辑:感谢timday用于突出显示 bug在保证不成立的 gcc/glibc 中。
编辑 2:Ben 的评论突出了一个有趣的边缘案例。分配程序的要求仅适用于标准提供的要求。如果应用程序有自己的版本,那么结果就没有这样的保证。
关于c++ - C++ 的新操作是否可以保证地址返回的对齐?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/506518/