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

◇◆丶佛笑我妖孽 提交于 2019-12-22 01:23:36

问题


It seems reasonable to assume that T and const T would be two types that would be the same size and have the same alignment, but after thinking about some real systems, it seems that they could be different.

Let me explain:

Suppose you have a system with two types of memory: RAM and Flash (which is read only). The RAM is 8 bit addressable, while the Flash is only 16 bit addressable. Suppose this is T:

struct T
{
  uint8_t x;
  uint16_t y;
};

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.

So here is my question:

Do the c and c++ standards guarantee the sizes and alignment of const and nonconst types?


回答1:


Section 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" here refers to const and volatile. So the answer is, yes.

const and volatile only specify the limitations/attributes of access to the specified object. They are not considered to be a part of the base type itself; hence they cannot affect the type's properties.




回答2:


Yes, this is guaranteed by [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:


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.

However, the compiler cannot infer that just because it's const here, it is stored in ROM. There's lots of other things that can prevent that, like mutable, or you could just dynamically place the const T on the stack or manually place it into heap memory in RAM or a thousand other things. You could also have a const T& that could be in either location.



来源:https://stackoverflow.com/questions/38799924/does-sizeoft-sizeofconst-t-and-alignoft-alignofconst-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!