Using iostream << to serialize user objects

倾然丶 夕夏残阳落幕 提交于 2019-12-10 23:59:58

问题


I want serialize object to binary file using operator "<<", but when I serialize, for example, int fields, I obtained it's symbolic representation:

ofstream out("file", ios::out | ios::binary);
int i=0xAA;
out << i;

And output:

0x31 0x37 0x30

i.e. (0xAA -> 170)

170

If I use write function, all ok:

out.write((char*)&i,sizeof(int));

Output:

0xAA 0x00 0x00 0x00

But can I use << instead write function, to serialize object? Like:

out << obj.field1 << obj.field2; // etc.

回答1:


First, a warning: You do know that the bytes within an int, or anything similar, depends on your compiler, computer, and operating system, right? Other systems might output bytes 0x00 0x00 0x00 0xAA for your example above, or something else entirely. Which means that if you send those bytes to a different computer and attempt to read them, you won't necessarily get your original int back.

Anyway. If you just want to spit out entire objects, one way to set this up would be to just define serialization for your class(es) and/or struct(s) by overloading operator<<:

std::ostream& operator<<(std::ostream& out, const MyClass& obj) {
  out.write(reinterpret_cast<const char*>(&obj.field1),
            sizeof(obj.field1)); // or something better defined
  // ...
  return out;
}

ofstream out("file", ios::out | ios::binary);
out << obj1 << obj2;



回答2:


For std::ostream and derived classes, operator<< is a formatted output function. write(), on the other hand, is an unformatted output function. So with ostreams, the answers is no.

On the other hand you could consider using Boost.Serialization, with which you can serialize to binary archives using << operator.



来源:https://stackoverflow.com/questions/3901209/using-iostream-to-serialize-user-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!