5

Given a struct that contains a sequence of the same fundamental types, like this:

struct Vector { float x; float y; float z; }; 

Can it have padding between the members? I was given the link to [class.mem] that says that padding may be added to achieve alignment but is it applicable in this case?

11
  • 1
    If the introduction of padding would be problematic for you, you can try to use static_assert to check at compile time. For example, static_assert(sizeof(Vector) == sizeof(float) * 3, "");. Commented May 11, 2017 at 15:03
  • 2
    I'm fairly sure that you cannot assume anything except that there is no padding before the first member, and that each individual type is correctly aligned. AFAIK padding between or after the members is conforming (though seemingly pointless). Commented May 11, 2017 at 15:03
  • 1
    @FrançoisAndrieux I'm not sure if it actually answer if there is a padding between the Vector members Commented May 11, 2017 at 15:04
  • 1
    @W.F. no it can't. If sizeof(Vector) is three floats, and we know that a Vector contains at least 3 floats, then that doesn't leave a single byte anywhere for padding. Commented May 11, 2017 at 15:10
  • 1
    @Donnie which is not that bad, given that users can fall down to compiler extensions to manipulate it. Commented May 11, 2017 at 15:13

1 Answer 1

2

It seems there are no technical reasons for floats in a struct be aligned differently than in an array. But still there is lack of standardization of C++ at the binary level.

If you want to be safe, then you can add a static_assert:

static_assert(offsetof(Vector, y) - offsetof(Vector, x) == sizeof(float)); static_assert(offsetof(Vector, z) - offsetof(Vector, y) == sizeof(float)); 

Moreover you are also able to disable padding with a not cross-platform way. For Visual Studio, you need #pragma pack and for gcc, you need to use an attribute packed.

Sign up to request clarification or add additional context in comments.

4 Comments

Can you provide a quote from the Standard? This is a language lawyer question.
@Lyberta There tend not to be quotes about lack-of-requirements
Is there certainly no way to make sure no padding occurs? This feels important enough to warrant a definitive answer.
@PasserBy And there is a definitive answer. Padding is implementation-defined. That's the end of it. And, while I'm not sure the second sentence in this answer would agree with me, that's a good thing. You want some way to control whether or not padding occurs? Read the documentation for your implementation.