motam79
motam79

Reputation: 3824

How to save a std::vector of C++ objects in binary format to disk?

I have vector of base class pointers of potentially heterogeneous objects (all derived from the same base class). I would like to save this vector to disk in a binary format. Is there a library in C++ to store object and stl containers in binary format?

Upvotes: 0

Views: 922

Answers (3)

Francis Cugler
Francis Cugler

Reputation: 7895

Consider this:

class Base {
protected:
    unsigned int id_;
protected:
    Base() {}
    virtual ~Base(){}
};

class DerivedA : public Base {
public:
    int someIntA_;
    short someShortA_;
};

class DerivedB : public Base {
public:
    int someIntB_;
    double someDoubleB_;
};

void writeToFile( const std::string& filename, std::vector<Base*>& objs ) {
    // first few elements in objs
    objs[0] = DerivedA;
    objs[1] = DerivedB;
    objs[2] = DerivedB;
    objs[3] = DerivedA;

    // how to pack & extract data in binary?
}

Your vector contains pointers to Base which depending on system and architect will determine the sizeof() a pointer type. Most systems have 4 bytes for a pointer type but this isn't guaranteed. However the data types at which these pointers point to are of their derived types. In memory sizeof(DerivedA) will be different than sizeof(DerivedB). You have to inform your C++ Compiler on how to parse this data in both writing to file and reading - extracting from file and this doesn't include any kind of compression techniques that may be used.

Now as for any auto generating libraries that will serialize your data for you; I'm not familiar of any off of the top of my head, but I have seen that others have given you some suggestions that may be worth looking into, otherwise you are on your own at writing to and from files according to your data types and their structures.

Upvotes: 0

gavinb
gavinb

Reputation: 20018

Is there a library in C++ to store object and stl containers in binary format?

Yes, Boost Serialisation does exactly this. One of the goals is:

  • Serialization of STL containers and other commonly used templates.

I wouldn't try reinventing this wheel - there's loads of corner cases and tricky problems in this area that have already been solved for you.

Upvotes: 2

Michael Surette
Michael Surette

Reputation: 711

I would suggest Google's protobuf library, which is designed just for solving this problem. It is binary, so not at all human readable. https://developers.google.com/protocol-buffers/

Upvotes: 0

Related Questions