Small Buffer Optimization and alignment

c++, c++11

Solution

It is not possible for the alignment of a type to be greater than the size of that type.

3.11 Alignment [basic.align]

[...] An alignment is an implementation-defined integer value representing the number of bytes between successive addresses at which a given object can be allocated.

5.3.3 Sizeof [expr.sizeof]

2 - [...] the size of an array of n elements is n times the size of an element.

So, your code can only break if `alignof(void *) < sizeof(void *)`, which is not the case on most platforms.

For safety, you can write:

template< typename Type >
struct is_small_pod
  : std::integral_constant<
        bool
      , std::is_pod< Type >::type::value
        && sizeof( Type ) <= sizeof( void* )
        && alignof( Type ) <= alignof( void* )
    >
{};

Problem

I am writing a C++ wrapper around a legacy API. This API provides me with a pointer value to keep extra data, and I want to implement the Small Buffer Optimization with it. I have implemented an `is_small_pod` metafunction that checks whether a given type is POD and it fits within a `void*`: ``` template< typename Type > struct is_small_pod : std::integral_constant< bool , std::is_pod< Type >::type::value && sizeof( Type ) <= sizeof( void* ) > {}; ``` and I'm setting the value like this: ``` // void*& param; if( detail::is_small_pod< Type >() ) { *static_cast< Type* >( &param ) = value; } else { param = new Type( value ); } ``` Am I implementing this optimization correctly? I believe this will fail when the value alignment is not compatible with the alignment of a pointer (odd corner case as it may be). Is that situation even possible, or am I just overthinking it? How should I extend my metafunction to check for compatible alignment as well?

Original source

Related problems