Is it safe to serialize a raw boost::variant?

╄→尐↘猪︶ㄣ 提交于 2019-12-17 19:44:48

问题


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.

Also, (probably) equivalently, can boost::variant be used in shared memory?


回答1:


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;
}

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.

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




回答2:


Try just including boost/serialization/variant.hpp; it does the work for you.



来源:https://stackoverflow.com/questions/1194842/is-it-safe-to-serialize-a-raw-boostvariant

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!