title: Why can't we trivially copy std::function
body: <p>The reason for me to ask this is I need to store <code>std::function</code> in a vector, and the in-house vector we have in company basically is doing realloc if it needs more memory. (Basically just <code>memcpy</code>, no copy/move operator involves)</p>
  
  <p>This means all the element we can put in our container need to be trivially-copyable.</p>
  
  <p>Here is some code to demonstrate the problematic copy I had:</p>
  
  <pre><code>void* func1Buffer = malloc(sizeof(std::function&lt;void(int)&gt;));
  std::function&lt;void(int)&gt;* func1p = new (func1Buffer) std::function&lt;void(int)&gt;();
  std::function&lt;void(int)&gt;* func2p = nullptr;
  *func1p = [](int) {};
  char func2Buffer[sizeof(*func1p)];
  memcpy(&amp;func2Buffer, func1p, sizeof(*func1p));
  func2p = (std::function&lt;void(int)&gt;*)(func2Buffer);
  // func2p is still valid here
  (*func2p)(10);
  free(func1Buffer);
  // func2p is now invalid, even without std::function&lt;void(int)&gt; desctructor get triggered
  (*func2p)(10);
  </code></pre>
  
  <p>I understand we should support copy/move of the element in order to store <code>std::function</code> safely.
  But I am still very curious about what is the direct cause of invalid <code>std::function</code> copy above.</p>
  
  <p><strong>----------------------------------------------------UpdateLine----------------------------------------------------</strong></p>
  
  <p>Updated the code sample.</p>
  
  <p>I have found the direct reason for this failure, by debugging our in-house vector more. </p>
  
  <p>The trivially copied <code>std::function</code> has some dependency on original object memory, delete the original memory will trash the badly copied <code>std::function</code> even <strong>without</strong> the destruction of the original object.</p>
  
  <p>Thanks for everyone's answer to this post. It's all valuable input. :)</p>