title: Small object stack storage, strict-aliasing rule and Undefined Behavior
body: <p>I am writing a type-erased function wrapper similar to <code>std::function</code>. (Yes, I have seen similar implementations and even the <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0288r0.pdf" rel="nofollow noreferrer">p0288r0</a> proposal, but my use-case is quite narrow and somewhat specialized.). The heavily simplified code below illustrates my current implementation:</p>
  
  <pre><code>class Func{
      alignas(sizeof(void*)) char c[64]; //align to word boundary
  
      struct base{
          virtual void operator()() = 0;
          virtual ~base(){}
      };
  
      template&lt;typename T&gt; struct derived : public base{
          derived(T&amp;&amp; t) : callable(std::move(t)) {} 
          void operator()() override{ callable(); }
          T callable;
      };
  
  public:
      Func() = delete;
      Func(const Func&amp;) = delete;
  
      template&lt;typename F&gt; //SFINAE constraints skipped for brevity
      Func(F&amp;&amp; f){
          static_assert(sizeof(derived&lt;F&gt;) &lt;= sizeof(c), "");
          new(c) derived&lt;F&gt;(std::forward&lt;F&gt;(f));
      }
  
      void operator () (){
          return reinterpret_cast&lt;base*&gt;(c)-&gt;operator()(); //Warning
      }
  
      ~Func(){
          reinterpret_cast&lt;base*&gt;(c)-&gt;~base();  //Warning
      }
  };
  </code></pre>
  
  <p><a href="http://coliru.stacked-crooked.com/a/fea4ed50d5cc890c" rel="nofollow noreferrer">Compiled</a>, GCC 6.1 warns about <a href="https://stackoverflow.com/questions/98650/what-is-the-strict-aliasing-rule">strict-aliasing</a> :</p>
  
  <pre><code>warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing]
           return reinterpret_cast&lt;T*&gt;(c)-&gt;operator()();
  </code></pre>
  
  <p>I also know about the <a href="https://stackoverflow.com/questions/98650/what-is-the-strict-aliasing-rule">strict-aliasing rule</a>. On the other hand, I currently do not know of a better way to make use of small object stack optimization. Despite the warnings, all my tests passes on GCC and Clang, (and an extra level of indirection prevents GCC's warning). My questions are:</p>
  
  <ul>
  <li>Will I eventually get burned ignoring the warning for this case?</li>
  <li>Is there a better way for in-place object creation?</li>
  </ul>
  
  <p>See full example: <a href="http://coliru.stacked-crooked.com/a/fea4ed50d5cc890c" rel="nofollow noreferrer">Live on Coliru</a></p>