Search code examples
c++language-lawyersizeof

Is it safe to assert(sizeof(A) == sizeof(B)) when A and B are "the same"?


Suppose I have two classes that I would expect to have exact same memory layout:

struct A {
    int x;
    int y;
};

/* possibly more code */

struct B {
    int a;
    int b;
};

Is there anything in the standard that guarantees that I can safely static_assert(sizeof(A) == sizeof(B)) ?

As a weaker variant consider

struct C {
    int a;
};

static_assert( sizeof(A) >= sizeof(C) );   // can this ever fail?
static_assert( sizeof(A) >  sizeof(C) );   // can this ever fail?

The question was triggered by this one. Naively I would not expect any of the asserts to fail, but is this guaranteed?


Solution

  • Nothing in the Standard would forbid an implementation which identified all the structures that are ever used as parts of unions, and added a random amount of padding after each element of any structure that was not used in such fashion. On the other hand, nothing would forbid an implementation from behaving in arbitrary fashion if the number of tags an implementation can handle, nor would anything forbid an implementation from imposing a limit of one.

    All of those things fall into the category of things that the Standard would allow a conforming implementation to do, but which quality implementations should generally be expected to refrain from doing even if allowed by the Standard. The Standard makes no effort to forbid implementations from doing silly things, nor to guess at whether some specialized implementations might have a good reasons for processing something in an atypical fashion. Instead, it expects that compiler writers will try to fulfill the needs of their customers whether or not the Standard requires them to do so.