【无标题】

错误代码

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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值