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

查看:129
本文介绍了是否有地址返回比对由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 ++防爆preSS 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 以突出显示的在gcc / glibc的错误那里的担保不成立。

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

编辑2 :奔的评论凸显了野趣边缘情况。上的分配例程的要求是为那些仅由标准设置。如果应用程序有它自己的版本,那么就对结果没有这样的保证。

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天全站免登陆