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

谁说胖子不能爱 提交于 2019-12-05 10:21:16

问题


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?


回答1:


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.




回答2:


A contrived counter-example:

#include <stdint.h>

struct A {
    int32_t a;
    int64_t b;
};

#pragma pack(4)

struct B {
    int32_t a;
    int64_t b;
};

static_assert(sizeof(A) == sizeof(B));

Compilation with g++ in 64-bit Linux yields:

a.cc:15:1: error: static assertion failed
static_assert(sizeof(A) == sizeof(B));



回答3:


The only instance where you assertion can be false is when there is a difference of packing criteria. Otherwise the assertion must be true.

The compiler only has the struct definition to work out member offset so the so unless the layoùt is consistent you would not be able access the struct.



来源:https://stackoverflow.com/questions/55068593/is-it-safe-to-assertsizeofa-sizeofb-when-a-and-b-are-the-same

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!