Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

c++ - Boost serialization bitwise serializability

I expect from is_bitwise_serializable trait to serialize class like following (without serialize function):

class A { int a; char b; };
BOOST_IS_BITWISE_SERIALIZABLE(A);
A a{2, 'x'};
some_archive << a; // serializes a bitwisely

I wonder, why is there a need to provide serialize function for bitwise_serializable class?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From the documentation:

Some simple classes could be serialized just by directly copying all bits of the class. This is, in particular, the case for POD data types containing no pointer members, and which are neither versioned nor tracked. Some archives, such as non-portable binary archives can make us of this information to substantially speed up serialization.

To indicate the possibility of bitwise serialization the type trait defined in the header file is_bitwise_serializable.hpp is used:

Here are the key points: this optimization

  • is optional in the archive types where it does apply
  • doesn't apply to all archive types e.g.

    • a binary archive that needs to be portable could not be implemented by copying out the raw memory representation (because it is implementation and platform depenedent)

    • a text archive might not desire to optimize this (e.g. it has different goals to, like "human readable XML", they might not want to encode your vector<A> as a large bas64 encoded blob).

Note that this also explains that is_bit_wise_serializable<T> is not partially specialized for any type that has is_pod<T>::value == true (This could technically be done easily):

  • some classes might not be interested in serializing all their state (so using bitwise copy would take a lot more space than just selecting the interesting bits (pun intended))

You didn't ask, specifically, but this is what the working implementation would look like:

#include <boost/archive/binary_oarchive.hpp>
#include <boost/serialization/serialization.hpp>
#include <sstream>

struct A { int a; char b;
    template <typename Ar> void serialize(Ar& ar, unsigned) {
        ar & a;
        ar & b;
    }
};

BOOST_IS_BITWISE_SERIALIZABLE(A)

int main() {
    std::ostringstream oss;
    boost::archive::binary_oarchive oa(oss);

    A data { 1, 'z' };
    oa << data;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...