【IT168技术文档】
持久对象(persistent objects)广泛应用于游戏、分布式数据库系统、多媒体以及图形应用程序中。目前C++并不直接支持持久性(persistence)(但有一些在C++未来版本中添加持久性和反射(reflection)的建议)。持久对象可以在创建它的程序的作用域之外保持自身状态。把对象写入一个文件并在以后重建之,或者把对象传送到一台远程机器,就是这样的例子。对持久性的支持并不象第一眼看上去那样简单,同一对象的大小和内存布局在不同的平台上可能并不相同,而不同的字节次序(byte ordering),或称为endian-ness,使事情更加复杂化。在下文中我将讨论如何实现持久性,而无须求助于DCOM和 CORBA之类的第三方框架。对于小型和可移植的应用程序而言,这是一种有效并令人满意的方案。
序列化(serialization)基础
为了使一个对象持久存在,必须把它的状态保存在非易失的存储设备中。考虑一个录制和播放MP3文件的应用程序,每首单曲都表示为一个包含标题、唱片、歌手、时间、速率、录制日期以及相应的 MP3文件的对象,该应用程序在跟踪列表中显示最近播放的曲目。你的目标是通过序列化,也就是把对象写入一个文件,使MP3对象成为持久对象,同时通过反序列化(deserialization)在下一个 session中重建这些对象。
序列化内置数据类型
每个对象最终都由内置数据成员组成,如int, bool, char[]等等。你的第一个任务是把这样的类型写入一个输出文件流(ofstream)中。应用程序必须这些值存储为相应的二进制形式,基于这个目的,应使用write() 和read() 成员函数。write() 以某个变量的地址和大小为参数,把该变量的位模式写入一个文件流中。read() 的两个参数为char*和long类型,分别指示内存缓冲区的地址和字节大小。下面的例子演示如何在ofstream中保存两个整数:
使用reinterpret_cast<>是必要的,因为write()的第一个参数类型为const char*,但&x和&y是int*类型。#include <fstream> using namespace std; int main() { int x,y; // mouse coordinates // ..assign values to x and y ofstream archive("coord.dat", ios::binary); archive.write(reinterpret_cast<char *>(&x), sizeof (x)); archive.write(reinterpret_cast<char *>(&x), sizeof (x)); archive.close(); }
以下代码读取刚才存储的值:
序列化对象#include <fstream> using namespace std; int main() { int x,y; ifstream archive("coord.dat"); archive.read((reinterpret_cast<char *>(&x), sizeof(x)); archive.read((reinterpret_cast<char *>(&y), sizeof(y)); }
要序列化一个完整的对象,应把每个数据成员写入文件中:
实现deserialize() 需要一些技巧,因为你需要为字符串分配一个临时缓冲区。做法如下:class MP3_clip { private: std::time_t date; std::string name; int bitrate; bool stereo; public: void serialize(); void deserialize(); //.. }; void MP3_clip::serialize() { int size=name.size();// store name's length //empty file if it already exists before writing new data ofstream arc("mp3.dat", ios::binary|ios::trunc); arc.write(reinterpret_cast<char *>(&date),sizeof(date)); arc.write(reinterpret_cast<char *>(&size),sizeof(size)); arc.write(name.c_str(), size+1); // write final '\0' too arc.write(reinterpret_cast<char *>(&bitrate), sizeof(bitrate)); arc.write(reinterpret_cast<char *>(&stereo), sizeof(stereo)); }
void MP3_clip::deserialize() { ifstream arce("mp3.dat"); int len=0; char *p=0; arc.read(reinterpret_cast<char *>(&date), sizeof(date)); arc.read(reinterpret_cast<char *>(&len), sizeof(len)); p=new char [len+1]; // allocate temp buffer for name arc.read(p, len+1); // copy name to temp, including '\0' name=p; // copy temp to data member delete[] p; arc.read(reinterpret_cast<char *>(&bitrate), sizeof(bitrate)); arc.read(reinterpret_cast<char *>(&stereo), sizeof(stereo)); }