Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I've never serialized a structure to a file before in C++, so I'm looking for critique on my first try at it.

My main concerns are:

  • It uses the streams space-delimited behavior. If a vector<char> that contains a space is serialized, it skips the space, which results in an exception. From my tests, it works fine for non-whitespace elements, but I'd like any suggestions on how I could circumvent this problem.

  • Should I be throwing an exception on bad reads? Am I throwing the right exception?

  • Should I be clearing the vector before adding to it while reading?

  • The string formatting for the runtime_errors is ugly. I didn't want to introduce a stringstream just to format the message.


#include <fstream>
#include <vector>
#include <string>
#include <stdexcept>

template <class T>
std::fstream& operator<<(std::fstream& fs, std::vector<T>& v) {
    //Write size of vector
    fs << v.size() << ' ';

    //Write contents
    for (T& t : v) {
        fs << t << ' ';
    }

    return fs;
}

template <class T>
std::fstream& operator>>(std::fstream& fs, std::vector<T>& v) {
    v.clear();

    unsigned int vSize;

    fs >> vSize;

    if (!fs.good()) {
        throw std::runtime_error(
            std::string("Problem reading serialized vector size: ").append(std::to_string(vSize)) 
        );
    }

    for (unsigned int i = 0; i < vSize; i++) {
        T readT;
        fs >> readT;

        if (!fs.good()) {
            unsigned long errPos = fs.tellg();
            throw std::runtime_error(
                std::string("Problem reading serialized vector content at ").append(std::to_string(errPos))
            );
        }

        v.push_back(readT);

    }
    return fs;
}
share|improve this question

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.