对于所有对象类型T,总是总是sizeof(T)> = alignof(T)吗? [英] Is it always the case that sizeof(T) >= alignof(T) for all object types T?

查看:90
本文介绍了对于所有对象类型T,总是总是sizeof(T)> = alignof(T)吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于任何对象类型T,是否总是总是sizeof(T)至少与alignof(T)一样大?

For any object type T is it always the case that sizeof(T) is at least as large as alignof(T)?

直觉上是这样,因为即使您调整对象的对齐方式,例如:

Intuitively it seems so, since even when you adjust the alignment of objects like:

struct small {
  char c;
};

通常,它们的大小"也要向上调整,以使数组中的对象之间的关系在保持对齐的同时有意义(至少在我的

above what it would normally be, their "size" is also adjusted upwards so that the relationship between objects in an array makes sense while maintaining alignment (at least in my testing. For example:

struct alignas(16) small16 {
  char c;
};

大小和对齐方式均为16.

Has both a size and alignment of 16.

推荐答案

至少在标准C ++中,对于任何您可以使数组(长度> 1)都必须为真的问题.如果有

At least in standard C++, for anything you can make an array of (with length > 1), this will have to be true. If you have

Foo arr[2];

alignof(Foo) > sizeof(Foo),则arr[0]arr[1]不能同时对齐.

and alignof(Foo) > sizeof(Foo), then arr[0] and arr[1] can't both be aligned.

但是,如 Zalman Stern的示例所示,至少某些编译器将允许您声明比其大小更大的对齐方式的类型. ,结果是编译器根本不允许您声明该类型的数组.这不是符合标准的C ++(它使用类型属性,该属性

As Zalman Stern's example shows, though, at least some compilers will allow you to declare a type with alignment greater than its size, with the result that the compiler simply won't let you declare an array of that type. This is not standards-compliant C++ (it uses type attributes, which are a GCC extension), but it means that you can have alignof(T) > sizeof(T) in practice.

array参数采用sizeof(Foo) > 0,这对于标准支持的任何类型都是正确的,但是 o11c显示了一个示例,其中编译器扩展破坏了保证:某些编译器允许使用0 sizeof和正数alignof的0长度数组.

The array argument assumes sizeof(Foo) > 0, which is true for any type supported by the standard, but o11c shows an example where compiler extensions break that guarantee: some compilers allow 0-length arrays, with 0 sizeof and positive alignof.

这篇关于对于所有对象类型T,总是总是sizeof(T)> = alignof(T)吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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