C++ 序列化库 Cereal使用(二)

阅读本文大概需要3分钟

cereal进阶

上一篇介绍了 cereal基本用法,可以满足基础的需求了,这里记录下一些注意事项.

  • 序列化函数在外部情况时,必须确保序列化函数和class在同一个变量域中

比如:

bool QDicomFilePrivate::loadDicomTagToFile(const QString &strFile)
{
    CHECK_POINTER_BOOL(m_pDicomTag);
bool bResult = false;

if (strFile.contains (".json"))
{
    std::ofstream os(strFile.toStdString ());
    cereal::JSONOutputArchive archive(os);

    archive(cereal::make_nvp("dicomTag" ,*m_pDicomTag));
}
else if (strFile.contains (".xml"))
{
    std::ofstream os(strFile.toStdString ());
    cereal::XMLOutputArchive archive(os);

    archive(cereal::make_nvp("dicomTag" ,*m_pDicomTag));
}

return bResult;

}

那么我的 QDicomTag对象的序列化函数也必须和QDicomFilePrivate在同一个变量域

void serialize(Archive &ar, QDicomTag &tag, std::uint32_t const &version)
{
	...
}
  • 反序列化时,必须确保传入的文件存在,不存在会抛出异常!

比如:

	std::ifstream os(strPath);
	cereal::JSONInputArchive archive(os);
MyData data;
archive(cereal::make_nvp("dicomTag",data));

如果strPath路径不存在,则会发生如下异常:

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
terminate called after throwing an instance of 'cereal::RapidJSONException'
  what():  rapidjson internal assertion failure: IsObject()

其他

参考文章

  • [cereal官方文档] 1

如果您对本文有任何问题,可以在下方留言,或者Email我.

猜你喜欢

转载自blog.csdn.net/u013704336/article/details/103588784
今日推荐