Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

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

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 even when you adjust the alignment of objects like:

struct small {
  char c;
};

above what it would normally be, their "size" is also adjusted upwards so that the relationship between objects in an array makes sense while maintaining alignment (at least in my testing. For example:

struct alignas(16) small16 {
  char c;
};

Has both a size and alignment of 16.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

At least in standard C++, for anything you can make an array of (with length > 1), this will have to be true. If you have

Foo arr[2];

and alignof(Foo) > sizeof(Foo), then arr[0] and arr[1] can't both be aligned.

As Zalman Stern's example shows, though, at least some compilers will allow you to declare a type with alignment greater than its size, with the result that the compiler simply won't let you declare an array of that type. This is not standards-compliant C++ (it uses type attributes, which are a GCC extension), but it means that you can have alignof(T) > sizeof(T) in practice.

The array argument assumes sizeof(Foo) > 0, which is true for any type supported by the standard, but o11c shows an example where compiler extensions break that guarantee: some compilers allow 0-length arrays, with 0 sizeof and positive alignof.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...