Is it safe to serialize a raw boost::variant?(序列化原始 boost::variant 是否安全?)
问题描述
boost::variant 声称它是一种值类型.这是否意味着简单地写出 boost::variant 的原始表示并稍后加载它是安全的,只要它只包含 POD 类型?假设它将由相同编译器和相同版本的 boost 编译的代码在相同的架构上重新加载.
boost::variant claims that it is a value type. Does this mean that it's safe to simply write out the raw representation of a boost::variant and load it back later, as long as it only contains POD types? Assume that it will be reloaded by code compiled by the same compiler, and same version of boost, on the same architecture.
另外,(可能)等价地,boost::variant 可以用在共享内存中吗?
Also, (probably) equivalently, can boost::variant be used in shared memory?
推荐答案
关于序列化:它应该有效,是的.但是为什么不使用boost::variant
的访问机制来写出variant中包含的实际类型呢?
Regarding serialisation: It should work, yes. But why don't you use boost::variant
's visitation mechanism to write out the actual type contained in the variant?
struct variant_serializer : boost::static_visitor<void> {
template <typename T>
typename boost::enable_if< boost::is_pod<T>, void>::type
operator()( const T & t ) const {
// ... serialize here, e.g.
std::cout << t;
}
};
int main() {
const boost::variant<int,char,float,double> v( '1' );
variant_serializer s;
boost::apply_visitor( s, v );
return 0;
}
关于共享内存:boost::variant
不执行堆分配,所以你可以像 int
一样将它放入共享内存,当然,假设适当的同步.
Regarding shared memory: boost::variant
does not perform heap allocations, so you can place it into shared memory just like an int
, assuming proper synchronisation, of course.
不用说,正如您所说,以上仅当变体只能包含 POD 类型时才有效.
Needless to say, as you said, the above is only valid if the variant can only contain POD types.
这篇关于序列化原始 boost::variant 是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:序列化原始 boost::variant 是否安全?


基础教程推荐
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01