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

后端 未结 4 1591
抹茶落季
抹茶落季 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:38

    #include 
    
    typedef double foo __attribute__ ((aligned (64)));
    alignas(64) double bar;
    double baz __attribute__ ((aligned (64)));
    
    int main(int argc, char *argv[]) {
        std::cout << "foo sizeof: " << sizeof(foo) << " alignof: " << alignof(foo) << "\n";
        std::cout << "bar sizeof: " << sizeof(bar) << " alignof: " << alignof(decltype(bar)) << "\n";
        std::cout << "baz sizeof: " << sizeof(baz) << " alignof: " << alignof(decltype(baz)) << "\n";
    }
    

    Compile with:

    clang++ -std=c++11 alignof_test.cpp -o alignof_test && ./alignof_test
    

    Output:

    foo sizeof: 8 alignof: 64
    bar sizeof: 8 alignof: 8
    baz sizeof: 8 alignof: 8
    

    So strictly speaking, no, but the above argument re: arrays has to be preserved.

提交回复
热议问题