boost :: serialization :: binary_object(void * t,size_t size)和boost :: serialization :: make_binary_object(void * t,size_t size)之间的区别是什么?
我如何使用它们来获取实际的输出二进制文件?
答案 0 :(得分:3)
欢迎您!
这是一个显示如何使用它的示例。
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/serialization/binary_object.hpp>
#include <boost/serialization/serialization.hpp>
#include <iostream>
#include <sstream>
using boost::serialization::make_binary_object;
enum class Example : uint8_t {
A = 1,
B = 2,
};
int main() {
std::stringstream stream;
boost::archive::binary_oarchive ar(stream, boost::archive::no_header);
auto data = Example::A;
ar << make_binary_object(&data, sizeof(data));
std::cout << "Size: " << stream.str().size() << "\n";
}
如果要将二进制对象保存在文件中,下面是一个将其保存在名为data.dat的文件中的示例
#include <fstream>
using boost::serialization::make_binary_object;
enum class Example : uint8_t {
A = 1,
B = 2,
};
int main() {
std::ofstream f("data.dat", std::ofstream::binary);
boost::archive::binary_oarchive ar(f, boost::archive::no_header);
auto data = Example::A;
ar << make_binary_object(&data, sizeof(data));
}
来自@StoryTeller发表的boost源代码注释
make_binary_object()只是一个小助手,可以支持所有序列化包装程序都遵循命名约定make_xxxxx
答案 1 :(得分:1)
boost::serialization::make_binary_object(void * t, size_t size)
是一个助手,并调用boost::serialization::binary_object(void * t, size_t size)
。提供了该助手来保留命名约定 make_xxxxx
要将对象保存到二进制文件,您需要创建一个Archive并调用void save(Archive & ar, const unsigned int /* file_version */)
的{{1}}方法