当A和B“相同"时断言(sizeof(A)== sizeof(B))是否安全? [英] Is it safe to assert(sizeof(A) == sizeof(B)) when A and B are "the same"?

查看:114
本文介绍了当A和B“相同"时断言(sizeof(A)== sizeof(B))是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个我希望它们具有完全相同的内存布局的类:

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;
};

该标准中是否有任何内容可以保证我可以安全地static_assert(sizeof(A) == sizeof(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?

推荐答案

标准中的任何内容都不能禁止一种实现,该实现可以标识曾经用作联合的一部分的所有结构,并在其中的每个元素之后添加随机的填充量没有以这种方式使用的任何结构.另一方面,如果一个实现可以处理的标签数量众多,则任何事情都不会阻止该实现的行为,也不能阻止一个实现施加一个限制.

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.

这篇关于当A和B“相同"时断言(sizeof(A)== sizeof(B))是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆