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
Release: 2024-12-08 18:57:13
Original
574 people have browsed it

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;
}
Copy after login

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template