How do you serialize an object in C++?

前端 未结 4 1150
天涯浪人
天涯浪人 2020-11-22 08:04

I have a small hierarchy of objects that I need to serialize and transmit via a socket connection. I need to both serialize the object, then deserialize it based on what ty

4条回答
  •  误落风尘
    2020-11-22 08:49

    In some cases, when dealing with simple types, you can do:

    object o;
    socket.write(&o, sizeof(o));
    

    That's ok as a proof-of-concept or first-draft, so other members of your team can keep working on other parts.

    But sooner or later, usually sooner, this will get you hurt!

    You run into issues with:

    • Virtual pointer tables will be corrupted.
    • Pointers (to data/members/functions) will be corrupted.
    • Differences in padding/alignment on different machines.
    • Big/Little-Endian byte ordering issues.
    • Variations in the implementation of float/double.

    (Plus you need to know what you are unpacking into on the receiving side.)

    You can improve upon this by developing your own marshalling/unmarshalling methods for every class. (Ideally virtual, so they can be extended in subclasses.) A few simple macros will let you to write out different basic types quite quickly in a big/little-endian-neutral order.

    But that sort of grunt work is much better, and more easily, handled via boost's serialization library.

提交回复
热议问题