错误代码
class HybridEngine {
public:
int a = 1;
template <class Archive>
void serialize(Archive & ar, uint32_t const version)
{
ar(a);
}
};
void test7() {
HybridEngine g, h;
std::shared_ptr<HybridEngine> gp = std::make_shared<HybridEngine>(g);
std::shared_ptr<HybridEngine> hp = nullptr;
gp->a = 2;
//hp->a = 5;
std::ofstream ofs("./test7.xar", std::ios::binary);
if (!ofs.is_open()) {
std::cerr << "Error: Failed to save " ;
}
cereal::BinaryOutputArchive oar(ofs);
oar(gp);
if (hp)
oar(hp);
ofs.close();
std::ifstream ifs("./test7.xar", std::ios::binary);
cereal::BinaryInputArchive iar(ifs);
iar(gp);
iar(hp);
ifs.close();
if (hp)
std::cout << "hp is not nullptr" << std::endl;;
std::cout << gp->a << std::endl;
//std::cout << hp->a << std::endl;
}
以上代码,hp是空指针,没有保存,再读取的时候,会崩
正确代码
class HybridEngine {
public:
int a = 1;
template <class Archive>
void serialize(Archive & ar, uint32_t const version)
{
ar(a);
}
};
void test7() {
HybridEngine g, h;
std::shared_ptr<HybridEngine> gp = std::make_shared<HybridEngine>(g);
std::shared_ptr<HybridEngine> hp = nullptr;
gp->a = 2;
//hp->a = 5;
std::ofstream ofs("./test7.xar", std::ios::binary);
if (!ofs.is_open()) {
std::cerr << "Error: Failed to save " ;
}
cereal::BinaryOutputArchive oar(ofs);
oar(gp);
oar(hp);
ofs.close();
std::ifstream ifs("./test7.xar", std::ios::binary);
cereal::BinaryInputArchive iar(ifs);
iar(gp);
iar(hp);
ifs.close();
if (hp)
std::cout << "hp is not nullptr" << std::endl;;
std::cout << gp->a << std::endl;
//std::cout << hp->a << std::endl;
}