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;
無論選擇哪種方法,都需要注意內存對齊和大小端序等問題,確保序列化和反序列化的正確性和可靠性。