C++: how to serialize/deserialize objects without the use of libraries?

后端 未结 2 1022
难免孤独
难免孤独 2020-12-28 09:29

I am trying to understand how serialization/deserialization works in C++ without the use of libraries. I started with simple objects but when deserializing a vector, I found

2条回答
  •  猫巷女王i
    2020-12-28 10:03

    One pattern is to implement an abstract class the defines functions for serialization and the class defines what goes into the serializer and what comes out. An example would be:

    class Serializable
    {
    public:
        Serializable(){}
        virtual ~Serializable(){}
    
        virtual void serialize(std::ostream& stream) = 0;
        virtual void deserialize(std::istream& stream) = 0;
    };
    

    You then implement Serializable interface for the class/struct that you want to serialize:

    struct PersonInfo : public Serializable // Yes! It's possible
    {
        unsigned int age_;
        string name_;
        enum { undef, man, woman } sex_;
    
        virtual void serialize(std::ostream& stream)
        {
            // Serialization code
            stream << age_ << name_ << sex_;
        }
    
        virtual void deserialize(std::istream& stream)
        {
            // Deserialization code
            stream >> age_ >> name_ >> sex_;
        }
    };
    

    Rest I believe you know. Here's a few hurdles to pass though and can be done in your leisure:

    1. When you write a string to the stream with spaces in it and try to read it back, you will get only one portion of it and rest of the string 'corrupts' the values read after that.
    2. How can you program it such that it's cross-platform (little-endian vs big-endian)
    3. How can your program automatically detect, which class to create when deserializing.

    Clues:

    1. Use custom serializer that has functions to write bool, int, float, strings, etc.
    2. Use a string to represent the object type being serialized and use factory to create an instance of that object when deserializing.
    3. Use predefined macros to determine which platform your code is being compiled.
    4. Always write files in a fixed endian and make the platforms that use the other endianess adjust to that.

提交回复
热议问题