Storing vector of pointers in a file and reading them again

眉间皱痕 提交于 2020-01-06 10:20:13

问题


Assume the following code:

// Base class
class Base {
public:
    Base(int val) : hi(val) {
    }
    virtual void PublicMethod() { /* Do something */}

private:
    int hi;
};

// Child class
class Child : public Base {
public:
    Child(int val) : Base(val) {
    }
    void PublicMethod() { /* Do something */}
};

// Vector of pointers to prevent slicing
std::vector<std::shared_ptr<Base>> list;

(...) // Fill list with mixed data of class Base and Child

After the list is filled with objects, I want to store the data into a file. For this I tried the following:

std::ofstream os("data.txt", std::ios::out);

int size1 = list.size();
os.write((const char*)&size1, sizeof(int));
for (auto it = list.begin(); it < list.end(); ++it) {
    os.write((const char*)(*it), size1 * sizeof(Base));
}
os.close();

However I am not sure if this is correct, and reading the data from the file also doesn't seem to work properly. I am afraid that when I'm saving the data sizeof(Base) also doesn't work for its child objects which might no be of the same size.

Even if this works correctly, are there better ways of storing the actual data into a file, and how can I easily read the data from the file and store them in a shared_ptr<Base> vector list?

Any examples would be of great help.


回答1:


You need to provide some form of serialization for your objects. Here's a very trivial example (that leaves out error checking, type construction etc.)

This example shows most primitive type of serialization, but it will suffice to provide an example of what you need to do.

When you start dealing with derived classes, it becomes more tricky, as you will need some factory method to properly create the types, based on some sentinel value that you serialize.

#include <string>
#include <iostream>
#include <sstream>
using namespace std;

class A
{
public:
    A()
        : a_(0)
    {
    }

    A(int a, const string& n)
        : a_(a), n_(n)
    {
    }

    // a function to write objects to a stream    
    friend ostream& operator<<(ostream& stream, const A& obj);

    // a function to read objects from a stream
    friend istream& operator>>(istream& stream, A& obj);

private:
    int a_;
    string n_;
};

ostream& operator<<(ostream& out, const A& obj)
{
    out << obj.a_ << ' ' << obj.n_;
    return out;
}

istream& operator>>(istream& in, A& obj)
{
    in >> obj.a_ >> obj.n_;
    return in;
}


int main()
{
    A one(1, "one");
    A also_one;

    string buffer;
    stringstream serializer;

    // write out your source object to a stream and "store it"
    // here we simply store it in a string    
    serializer << one;
    buffer = serializer.str();

    // using the "stored" value, read the stored values
    // into an (already constructed) object
    stringstream deserializer(buffer);
    serializer >> also_one;

    // verify the output is the same
    cout << one << " is the same as " << also_one << "\n";
}


来源:https://stackoverflow.com/questions/19729538/storing-vector-of-pointers-in-a-file-and-reading-them-again

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