Home >Backend Development >C++ >How to Serialize a C Class Containing an std::string?

How to Serialize a C Class Containing an std::string?

DDD
DDDOriginal
2024-12-08 18:57:13595browse

How to Serialize a C   Class Containing an std::string?

Serializing a Class with an std::string

Serializing a class that contains an std::string presents challenges due to the string's pointer-based nature. The standard technique of casting the class to a char* and writing it to a file won't work, as it does for primitive data types.

Custom Serialization Functions

A standard workaround involves creating custom serialization and deserialization functions for the class. These functions handle the reading and writing of the class data in a controlled manner.

Example Functions

For a class containing an std::string named "name", the serialization and deserialization functions could be implemented as follows:

std::ostream& MyClass::serialize(std::ostream& out) const {
    out << height;
    out << ',' // number separator
    out << width;
    out << ',' // number separator
    out << name.size(); // serialize size of string
    out << ',' // number separator
    out << name; // serialize characters of string
    return out;
}

std::istream&amp; MyClass::deserialize(std::istream&amp; in) {
    if (in) {
        int len = 0;
        char comma;
        in >> height;
        in >> comma; // read in the separator
        in >> width;
        in >> comma; // read in the separator
        in >> len; // deserialize size of string
        in >> comma; // read in the separator
        if (in &amp;&amp; len) {
            std::vector<char> tmp(len);
            in.read(tmp.data(), len); // deserialize characters of string
            name.assign(tmp.data(), len);
        }
    }
    return in;
}

Overloading Stream Operators

For easier use, you can overload the stream operators for your class:

std::ostream &amp;operator<<(std::ostream&amp; out, const MyClass &amp;obj) {
    obj.serialize(out);
    return out;
}

std::istream &amp;operator>>(std::istream&amp; in, MyClass &amp;obj) {
    obj.deserialize(in);
    return in;
}

With these functions and overloads, you can now serialize and deserialize a class containing an std::string by simply using the stream operators.

The above is the detailed content of How to Serialize a C Class Containing an std::string?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn