Let's imagine that we are writing some serialization function that stores values in a buffer of a specified size:
#include <cstring>
#include <boost/array.hpp>
// C++17 has std::byte out of the box!
// Unfortunately this is as C++03 example.
typedef unsigned char byte_t;
template <class T, std::size_t BufSizeV>
void serialize_bad(const T& value, boost::array<byte_t, BufSizeV>& buffer) {
// TODO: check buffer size.
std::memcpy(&buffer[0], &value, sizeof(value));
}
This code has the following problems:
- The size of the buffer is not checked, so it may overflow
- This function can be used with non-trivially copyable 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_bad(const T& value...