C++ 的新操作是否有任何保证地址返回对齐的保证? [英] Is there any guarantee of alignment of address return by C++'s new operation?

查看:37
本文介绍了C++ 的新操作是否有任何保证地址返回对齐的保证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大多数有经验的程序员都知道数据对齐对于程序的性能很重要.我见过一些程序员编写的程序分配比他们需要的更大的缓冲区大小,并使用对齐的指针作为开始.我想知道我是否应该在我的程序中这样做,我不知道是否有任何保证 C++ 的新操作返回的地址对齐.所以我写了一个小程序来测试

Most of experienced programmer knows data alignment is important for program's performance. I have seen some programmer wrote program that allocate bigger size of buffer than they need, and use the aligned pointer as begin. I am wondering should I do that in my program, I have no idea is there any guarantee of alignment of address returned by C++'s new operation. So I wrote a little program to test

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.看来新操作返回的所有地址都是对齐的.但我不确定.所以我的问题是:有任何保证吗?如果他们有保证,我就不必对齐,如果没有,我必须对齐.

The compiler I am using is Visual C++ Express 2008. It seems that all addresses the new operation returned are aligned. But I am not sure. So my question is: are there any guarantee? If they do have guarantee, I don't have to align myself, if not, I have to.

推荐答案

对齐方式从标准 (3.7.3.1/2) 有以下保证:

The alignment has the following guarantee from the standard (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 中,保证不成立.

EDIT: Thanks to timday for highlighting a bug in gcc/glibc where the guarantee does not hold.

EDIT 2:Ben 的评论强调了一个有趣的边缘情况.对分配例程的要求仅适用于标准提供的那些.如果应用程序有自己的版本,那么结果就没有这样的保证.

EDIT 2: Ben's comment highlights an intersting edge case. The requirements on the allocation routines are for those provided by the standard only. If the application has it's own version, then there's no such guarantee on the result.

这篇关于C++ 的新操作是否有任何保证地址返回对齐的保证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆