Cereal JSON 输出错过了右大括号
Cereal JSON output misses closing curly brace
我正在使用文档中给出的 Cereal C++ v1.1.1 and similar to the example 我正在尝试以下操作:
#include <sstream>
#include <iostream>
#include <cereal/archives/json.hpp>
int main() {
std::ostringstream os;
cereal::JSONOutputArchive archive(os);
int x = 12;
archive(CEREAL_NVP(x));
std::cout << os.str(); // JUST FOR DEMONSTRATION!
}
我希望有以下内容:
{
"x":12
}
但是缺少右大括号。知道代码中缺少什么吗?
更新:
添加archive.finishNode()
似乎可以解决问题。但我会说这不是解决方案。根据operator()
文档,调用operator会序列化输入参数,为什么要额外添加finishNode
?
我遇到了同样的问题,并在对 Cereal GitHub 上提交的问题的评论中找到了解决方案:https://github.com/USCiLab/cereal/issues/101
The documentation states "Archives are designed to be used in an RAII
manner and are guaranteed to flush their contents only on
destruction..." (http://uscilab.github.io/cereal/quickstart.html).
Your problem is that you are trying to print the contents of the
stringstream before the archive has been destroyed. At this point, the
archive has no idea whether you will want to write more data to it in
the future, so it refrains from streaming out the closing brace. You
need to make sure the archive's destructor has been called before
printing out the stringstream.
Try this:
int main()
{
std::stringstream ss;
{
cereal::JSONOutputArchive archive( ss );
SomeData myData;
archive( myData );
}
std::cout << ss.str() << std::endl;
return 0;
}
Please see the documentation for more information.
我正在使用文档中给出的 Cereal C++ v1.1.1 and similar to the example 我正在尝试以下操作:
#include <sstream>
#include <iostream>
#include <cereal/archives/json.hpp>
int main() {
std::ostringstream os;
cereal::JSONOutputArchive archive(os);
int x = 12;
archive(CEREAL_NVP(x));
std::cout << os.str(); // JUST FOR DEMONSTRATION!
}
我希望有以下内容:
{
"x":12
}
但是缺少右大括号。知道代码中缺少什么吗?
更新:
添加archive.finishNode()
似乎可以解决问题。但我会说这不是解决方案。根据operator()
文档,调用operator会序列化输入参数,为什么要额外添加finishNode
?
我遇到了同样的问题,并在对 Cereal GitHub 上提交的问题的评论中找到了解决方案:https://github.com/USCiLab/cereal/issues/101
The documentation states "Archives are designed to be used in an RAII manner and are guaranteed to flush their contents only on destruction..." (http://uscilab.github.io/cereal/quickstart.html).
Your problem is that you are trying to print the contents of the stringstream before the archive has been destroyed. At this point, the archive has no idea whether you will want to write more data to it in the future, so it refrains from streaming out the closing brace. You need to make sure the archive's destructor has been called before printing out the stringstream.
Try this:
int main() { std::stringstream ss; { cereal::JSONOutputArchive archive( ss ); SomeData myData; archive( myData ); } std::cout << ss.str() << std::endl; return 0; }
Please see the documentation for more information.