省略指向结构的指针的前向声明是否有效? [英] Is the omission of a forward declaration for a pointer to a structure valid?
问题描述
我最近遇到了此评论,作者: @Paul Ogilvie :
I recently came across this comment by @Paul Ogilvie:
"您说要定义指向结构的指针,您只需知道结构标签".根据我的经验,这是不必要的.只需声明一个pointer_to_some_type,编译器将为指针保留空间并在赋值时进行类型检查.仅在您要取消引用指针并访问其成员之后,才必须完全知道该类型."
"You say "To define a pointer to a structure you only need to know the structure tag". In my experience that is unnecessary. Just declare a pointer_to_some_type and the compiler will reserve space for a pointer and does type checking on assignment. Only once you want dereference the pointer and access its members, must the type fully be known."
我尝试过:
struct foo {
int a;
struct bar* x;
};
struct bar {
int b;
};
实际上,GCC和Clang都不会抛出任何诊断,这与尝试在不进行前向声明的情况下定义相应结构的对象相反.
and indeed neither GCC nor Clang doesn't throw any diagnostic, as opposed to attempt to defining an object of the respective struct without forward-declaration.
但这让我感到奇怪:这符合标准吗?
But that makes me wonder: Is this standard-compliant?
该标准的引用受到高度赞赏.
Citations from the standard are highly appreciated.
推荐答案
如果表示形式相同,则表示大小相同.
If the representations are the same, that implies that the sizes are the same.
存储在任何其他对象类型的非位字段对象中的值[ed.不是未签名的字符]由
n×CHAR_BIT
位组成,其中 n 是对象的大小该类型(以字节为单位).该值可以复制到一个类型的对象中unsigned char [n]
(例如,通过memcpy
);结果字节集为称为值的对象表示形式.位字段由 m 位组成,其中 m 是指定的大小对于位域.对象表示形式是该位字段包含 m 位,该位包含该位字段.相同的Tw o值(NaN除外)对象表示比较相等,但比较的值相等可能具有不同的对象表示形式.
Values stored in non-bit-field objects of any other object type [ed. not unsigned char] consist of
n×CHAR_BIT
bits, where n is the size of an object of that type, in bytes. The value may be copied into an object of typeunsigned char [n]
(e.g., bymemcpy
); the resulting set of bytes is called the object representation of the value. Values stored in bit-fields consist of m bits, where m is the size specified for the bit-field. The object representation is the set of m bits the bit-field comprises in the addressable storage unit holding it. Tw o values (other than NaNs) with the same object representation compare equal, but values that compare equal may have different object representations.
作为示例,gcc下的 int
和 short
都使用二进制补码,但是它们没有相同的对象表示形式,因为一个是4个字节,另一个是是2个字节.
As an example, an int
and a short
under gcc both use two's complement but they don't have the same object representation because one is 4 bytes and the other is 2 bytes.
这篇关于省略指向结构的指针的前向声明是否有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!