Is it always the case that sizeof(T) >= alignof(T) for all object types T?

后端 未结 4 1593
抹茶落季
抹茶落季 2020-12-05 01:51

For any object type T is it always the case that sizeof(T) is at least as large as alignof(T)?

Intuitively it seems so, since

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-05 02:37

    According to the c++ 11 standard that introduced the alignof operator, sizeof is defined as following (see 5.3.3 expr.sizeof):

    The sizeof operator yields the number of bytes in the object representation of its operand

    Whereas alignof definition is (see 5.3.6 expr.alignof):

    An alignof expression yields the alignment requirement of its operand type.

    Since the defintion of alignof specifies a requirement, possibly made by the user, rather than a specification of the language, we can manipulate the compiler:

    typedef uint32_t __attribute__ ((aligned (64))) aligned_uint32_t;
    std::cout << sizeof(aligned_uint32_t) << " -> " << alignof(aligned_uint32_t);
    // Output: 4 -> 64
    

    Edited

    As others have pointed out, such types cannot be used in arrays, e.g trying to compile the following:

    aligned_uint32_t arr[2];
    

    Results in error: alignment of array elements is greater than element size

    Since arrays require the specified type to conform with the condition: sizeof(T) >= alignof(T)

提交回复
热议问题