Is it safe to serialize the original boost :: variant?

boost :: variant claims to be a value type. Does this mean that it is safe to simply write out the raw representation of boost :: variant and load it later if it contains only POD types? Suppose it is reloaded with code compiled by the same compiler and the same version of boost, in the same architecture.

Also, (possibly) equivalent, can boost :: variant be used in shared memory?

+6
c ++ boost shared-memory serialization boost-variant
source share
2 answers

As for serialization: it should work, yes. But why don't you use the boost::variant visit mechanism to write the actual type contained in this 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, eg std::cout << t; } }; int main() { const boost::variant<int,char,float,double> v( '1' ); variant_serializer s; boost::apply_visitor( s, v ); return 0; } 

As for shared memory: boost::variant does not perform heap allocation, so you can put it in shared memory just like int , assuming proper synchronization, of course.

Needless to say, as you said, the above is only valid if the variant can only contain POD types.

+6
source share

Try turning on boost / serialization / variant.hpp; it does the job for you.

+14
source share

All Articles