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

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

Linda Hamilton
Release: 2024-12-05 12:33:14
Original
952 people have browsed it

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

Serializing a Class with an std::string

In C , serializing objects often involves casting the object to a character array (char*) and writing it to a file. This approach works well for simple data types like integers, but issues arise when dealing with dynamic data structures like the std::string.

When the serialized object is deserialized, the std::string contained within may point to memory that no longer exists, leading to an "address out of bounds" error.

To address this issue, a standard workaround is to implement custom serialization and deserialization methods within the class itself. These methods can manually serialize and deserialize the std::string's size and characters.

Implementation:

class MyClass {
    int height;
    int width;
    std::string name;

public:
    std::ostream& operator<<(std::ostream& out) const {
        out << height << ',' << width << ',' << name.size() << ',' << name;
        return out;
    }
    std::istream& operator>>(std::istream& in) {
        int len = 0;
        char comma;
        in >> height >> comma >> width >> comma >> len >> comma;
        if (len) {
            std::vector<char> tmp(len);
            in.read(tmp.data(), len);
            name.assign(tmp.data(), len);
        }
        return in;
    }
};
Copy after login

Usage:

MyClass obj;
obj.height = 10;
obj.width = 15;
obj.name = "MyClass";

// Serialize to file
std::ofstream outfile("myclass.dat");
outfile << obj;
outfile.close();

// Deserialize from file
std::ifstream infile("myclass.dat");
infile >> obj;
infile.close();
Copy after login

This custom approach ensures that the std::string is correctly serialized and deserialized. Additionally, it provides a convenient way to serialize and deserialize objects using the stream operators (<< and >>).

The above is the detailed content of How to Safely Serialize and Deserialize 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template