Search code examples
c++serializationboostmutableboost-serialization

boost::serialization with mutable members


Using boost::serialization, what's the "best" way to serialize an object that contains cached, derived values in mutable members?

class Example
{
public:
    Example(float n) : 
        num(n),
        sqrt_num(-1.0)
    {}

    // compute and cache sqrt on first read
    float get_sqrt() const
    { 
        if(sqrt_num < 0) 
            sqrt_num = sqrt(num);
        return sqrt_num;
    }

    template <class Archive> 
    void serialize(Archive& ar, unsigned int version)
    { ... }
private:
    float num;
    mutable float sqrt_num;
};

I'd like to avoid splitting serialize() into separate save() and load() methods, for maintenance reasons.

One suboptimal implementation of serialize:

    template <class Archive> 
    void serialize(Archive& ar, unsigned int version)
    {
        ar & num;
        sqrt_num = -1.0;
    }

This handles the deserialization case, but in the serialization case, the cached value is killed and must be recomputed.

What is the best practice in this case?


Solution

  • You can check the Archive::is_loading field, and load cached values if it's true.

    template <class Archive> 
    void serialize(Archive& ar, unsigned int version)
    {
        ar & num;
        if(Archive::is_loading::value == true)
            sqrt_num = -1.0;
    }