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

独自空忆成欢 提交于 2019-12-04 22:13:35

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.

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).

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.

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