Could it be the case that sizeof(T*) != sizeof(const T*)?

前端 未结 4 910
遥遥无期
遥遥无期 2021-02-06 20:30

I\'m arguing with my boss about this. They say \"Yes they can be different.\"

Is it possible that sizeof(T*) != sizeof(const T*) for a type T?<

4条回答
  •  迷失自我
    2021-02-06 20:39

    No, they can't be different. For sufficiently different T1 and T2, sizeof(T1 *) can be different from sizeof(T2 *), but if T2 is just const T1, then:

    3.9.2 Compound types [basic.compound]

    3 [...] Pointers to cv-qualified and cv-unqualified versions (3.9.3) of layout-compatible types shall have the same value representation and alignment requirements (3.11). [...]

    And any type T is layout-compatible with itself:

    3.9 Types [basic.types]

    11 If two types T1 and T2 are the same type, then T1 and T2 are layout-compatible types. [...]


    Value representation is in relation to the object representation, you can't have the same value representation without also having the same object representation. The latter means the same number of bits is required.

    3.9 Types [basic.types]

    4 The object representation of an object of type T is the sequence of N unsigned char objects taken up by the object of type T, where N equals sizeof(T). The value representation of an object is the set of bits that hold the value of type T. For trivially copyable types, the value representation is a set of bits in the object representation that determines a value, which is one discrete element of an implementation-defined set of values.44

    44) The intent is that the memory model of C++ is compatible with that of ISO/IEC 9899 Programming Language C.

    The point of the requirement, the reason it doesn't just say that the two types have the same object representation, is that T * and const T * not only have the same number of bits, but also that it's the same bits in T * and const T * that make up the value. This is meant to guarantee not only that sizeof(T *) == sizeof(const T *), but it means even that you can use memcpy to copy a T * pointer value to a const T * pointer value or vice versa and get a meaningful result, the exact same result you would get with const_cast.

    The alignment requirements provide some additional guarantees too, but they're complicated to explain properly and not directly relevant to this question, and there are issues in the standard that undermine some of the intended guarantees, so I think that's best left ignored here.

提交回复
热议问题