The Boost C++ Libraries

Wrapper Functions for Optimization

This section introduces wrapper functions to optimize the serialization process. These functions mark objects to allow Boost.Serialization to apply certain optimization techniques.

Example 64.14. Serializing an array without a wrapper function
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/array.hpp>
#include <iostream>
#include <sstream>

using namespace boost::archive;

std::stringstream ss;

void save()
{
  text_oarchive oa{ss};
  boost::array<int, 3> a{{0, 1, 2}};
  oa << a;
}

void load()
{
  text_iarchive ia{ss};
  boost::array<int, 3> a;
  ia >> a;
  std::cout << a[0] << ", " << a[1] << ", " << a[2] << '\n';
}

int main()
{
  save();
  load();
}

Example 64.14 uses Boost.Serialization without any wrapper function. The example creates and writes the value 22 serialization::archive 11 0 0 3 0 1 2 to the string. Using the wrapper function boost::serialization::make_array(), the value written can be shortened to the following string: 22 serialization::archive 11 0 1 2.

Example 64.15. Serializing an array with the wrapper function make_array()
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/array.hpp>
#include <array>
#include <iostream>
#include <sstream>

using namespace boost::archive;

std::stringstream ss;

void save()
{
  text_oarchive oa{ss};
  std::array<int, 3> a{{0, 1, 2}};
  oa << boost::serialization::make_array(a.data(), a.size());
}

void load()
{
  text_iarchive ia{ss};
  std::array<int, 3> a;
  ia >> boost::serialization::make_array(a.data(), a.size());
  std::cout << a[0] << ", " << a[1] << ", " << a[2] << '\n';
}

int main()
{
  save();
  load();
}

boost::serialization::make_array() expects the address and the length of an array. However, because it is known in advance, the length does not need to be serialized as part of the array.

boost::serialization::make_array() can be used whenever classes such as std::array or std::vector contain an array that can be serialized directly. Additional member variables, which would normally also be serialized, are skipped (see Example 64.15).

Boost.Serialization also provides the wrapper boost::serialization::make_binary_object(). Similar to boost::serialization::make_array(), this function expects an address and a length. boost::serialization::make_binary_object() is used solely for binary data that has no underlying structure, while boost::serialization::make_array() is used for arrays.