O'Reilly logo

Boost C++ Application Development Cookbook by Antony Polukhin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Checking sizes at compile time

Let's imagine that we are writing some serialization function that stores values in buffer of a specified size:

#include <cstring>
#include <boost/array.hpp>

template <class T, std::size_t BufSizeV>
void serialize(const T& value, boost::array<unsigned char, BufSizeV>& buffer) {
    // TODO: fixme
    std::memcpy(&buffer[0], &value, sizeof(value));
}

This code has the following troubles:

  • The size of the buffer is not checked, so it may overflow
  • This function can be used with non-plain old data (POD) types, which would lead to incorrect behavior

We may partially fix it by adding some asserts, for example:

template <class T, std::size_t BufSizeV> void serialize(const T& value, boost::array<unsigned char, BufSizeV>& buffer) { assert(BufSizeV ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required