sizeof(T) == sizeof(const T) 和 alignof(T) == alignof(const T)

Does sizeof(T) == sizeof(const T) and alignof(T) == alignof(const T)

假设 Tconst T 是两种大小相同且对齐方式相同的类型似乎是合理的,但在考虑了一些实际系统之后,似乎它们可能会有所不同。

让我解释一下:

假设您的系统有两种类型的内存:RAM 和闪存(只读)。 RAM 是 8 位可寻址的,而闪存只有 16 位可寻址。假设这是 T:

struct T
{
  uint8_t x;
  uint16_t y;
};

在字节可寻址 RAM 中,该结构的长度为 3 个字节....但在双字节可寻址闪存(const 变量所在的位置)中,该结构必须至少为4 个字节长,因为对齐问题。

所以这是我的问题:

c 和 c++ 标准是否保证 const 和非 const 类型的大小和对齐方式?

是的,这是由 [basic.type.qualifier] / 1

保证的

The cv-qualified or cv-unqualified versions of a type are distinct types; however, they shall have the same representation and alignment requirements (3.11).

第 3.9.3 节:

The cv-qualified or cv-unqualified versions of a type are distinct types; however, they shall have the same representation and alignment requirements (3.11). 53

这里的

"cv-qualified"指的是constvolatile。所以答案是肯定的。

constvolatile只指定limitations/attributes访问指定对象。它们不被认为是基类型本身的一部分;因此它们不会影响类型的属性。

In the byte addressable RAM this struct would be 3 bytes long.... but in the double byte addressable Flash (which is where a const variable would reside) this struct would have to be at least 4 bytes long, because of alignment issues.

然而,编译器不能推断仅仅因为它在const这里,它就存储在ROM中。有很多其他东西可以防止这种情况发生,例如 mutable,或者您可以动态地将 const T 放在堆栈上,或者手动将其放入 RAM 中的堆内存或其他一千种东西。您还可以有一个 const T& 可以位于任一位置。