C++中的POD類型(Plain Old Data)是指沒有構(gòu)造函數(shù)、析構(gòu)函數(shù)和虛函數(shù)的簡單數(shù)據(jù)類型,如基本數(shù)據(jù)類型和結(jié)構(gòu)體。對(duì)于POD類型的序列化,可以通過以下方法實(shí)現(xiàn):
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;
無論選擇哪種方法,都需要注意內(nèi)存對(duì)齊和大小端序等問題,確保序列化和反序列化的正確性和可靠性。