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& MyClass::deserialize(std::istream& 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 && 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 &operator<<(std::ostream& out, const MyClass &obj) { obj.serialize(out); return out; } std::istream &operator>>(std::istream& in, MyClass &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!