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?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With