“这”是否保证指向C中的对象的开始?

前端之家收集整理的这篇文章主要介绍了“这”是否保证指向C中的对象的开始?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想使用fwrite将一个对象写入顺序文件.班级就像
class A{
    int a;
    int b;
public:
    //interface
}

当我将一个对象写入文件时.我正在游荡,我可以使用fwrite(this,sizeof(int),2,fo)写入前两个整数.

问题是:这是否保证指向对象数据的开始,即使对象的最开始可能存在虚拟表.所以上面的操作是安全的.

解决方法

这提供了对象的地址,这不一定是第一个成员的地址.唯一的例外是所谓的标准布局类型.从C11标准:

(9.2/20) A pointer to a standard-layout struct object,suitably converted using a reinterpret_cast,points to its initial member (or if that member is a bit-field,then to the unit in which it resides) and vice versa. [ Note: There might therefore be unnamed padding within a standard-layout struct object,but not at its beginning,as necessary to achieve appropriate alignment. — end note ]

这是标准布局类型的定义:

(9/7) A standard-layout class is a class that:
— has no non-static data members of type non-standard-layout class (or array of such types) or reference,
— has no virtual functions (10.3) and no virtual base classes (10.1),
— has the same access control (Clause 11) for all non-static data members,
— has no non-standard-layout base classes,
— either has no non-static data members in the most derived class and at most one base class with non-static data members,or has no base classes with non-static data members,and
— has no base classes of the same type as the first non-static data member.[108]

[108] This ensures that two subobjects that have the same class type and that belong to the same most derived object are not allocated at the same address (5.10).

请注意,对象类型不一定是POD – 具有如上定义的标准布局就足够了. (POD都有标准布局,但是这些都是trivially constructible,平常可移动,可以复制).

就我从代码中可以看出,您的类型似乎是标准布局(确保所有非静态数据成员的访问控制是相同的).在这种情况下,这确实会指向初始成员.关于将其用于序列化的目的,标准实际上明确表示:

(9/9) [ Note: Standard-layout classes are useful for communicating with code written in other programming languages. Their layout is specified in 9.2. — end note ]

当然这并不能解决所有的序列化问题.特别是,您不会获得序列化数据的可移植性(例如由于字节不兼容).

原文链接:https://www.f2er.com/c/115324.html

猜你在找的C&C++相关文章