“这”是否保证指向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 ]

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

相关文章

首先GDB是类unix系统下一个优秀的调试工具, 当然作为debug代...
1. C语言定义1个数组的时候, 必须同时指定它的长度.例如:int...
C++的auto关键字在C+⬑新标准出来之前基本...
const关键字是用于定义一个不该被改变的对象,它的作用是告诉...
文章浏览阅读315次。之前用C语言编过链表,这几天突然想用C+...
文章浏览阅读219次。碰到问题就要记录下来,防止遗忘吧。文章...