Sogartar
Sogartar

Reputation: 2175

boost: serialization of shared_ptr with custom deleter

I am almost certain that boost serialization can not handle custom deleter in either boost::shared_ptr or std::shared_ptr. You would have to of course write serialization for the deleter. There is type erasure for the deleter similar to std::function, which can not be serialized.

One of the problems is that you can`t deduce the type of the deleter at runtime. If it was possible you could use a map with deleter types and serialization handlers.

The only other ugly approach that I can think of is to assume that all deleters are derived from a common base class and register derived classes for serialization.

Is there a more elegant solution that does not require a common base?

Upvotes: 1

Views: 111

Answers (1)

sehe
sehe

Reputation: 394054

The only other ugly approach that I can think of is to assume that all deleters are derived from a common base class

This is exactly it. This is the only way to do it, given the way you framed the question.

However, you can of course transpose the design, and make the deleter fixed. The differences in behaviour could be driven from the element_type member data.

So, if you make the element type contain the non-erased deleter, you can

  1. simply include the serialization thereof as part of the object
  2. write an "actual" deleter to relay to it, e.g.:

    template <typename T>
    struct InvertedDeleter {
        void operator()(T* element) const {
            element->get_deleter()(element);
        }
    };
    

Upvotes: 1

Related Questions