C++中的POD类型(Plain Old Data)是指没有构造函数、析构函数和虚函数的简单数据类型,如基本数据类型和结构体。对于POD类型的序列化,可以通过以下方法实现:
struct PodType {
int intValue;
float floatValue;
};
// Serialize
PodType podObject = {10, 3.14};
std::ofstream outFile("data.bin", std::ios::binary);
outFile.write(reinterpret_cast<char*>(&podObject), sizeof(PodType));
outFile.close();
// Deserialize
PodType deserializedObject;
std::ifstream inFile("data.bin", std::ios::binary);
inFile.read(reinterpret_cast<char*>(&deserializedObject), sizeof(PodType));
inFile.close();
#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/serialization/vector.hpp>
struct PodType {
int intValue;
float floatValue;
template<class Archive>
void serialize(Archive & ar, const unsigned int version) {
ar & intValue;
ar & floatValue;
}
};
// Serialize
PodType podObject = {10, 3.14};
std::ofstream outFile("data.bin", std::ios::binary);
boost::archive::binary_oarchive oa(outFile);
oa << podObject;
// Deserialize
PodType deserializedObject;
std::ifstream inFile("data.bin", std::ios::binary);
boost::archive::binary_iarchive ia(inFile);
ia >> deserializedObject;
无论选择哪种方法,都需要注意内存对齐和大小端序等问题,确保序列化和反序列化的正确性和可靠性。