title: Capturing pointer by value in nested lambda leads to segfault
body: <p>First of all, this is the most obscure problem I have ever had and thus is the hardest question to ask. I'll try make this question as articulate as possible by posting minimal code and providing some context. First of all here is the code where the problem occurs:</p>
  
  <pre><code>// Before lambda, pointer variable in question is fine
  menu-&gt;onSelect = [=] ()
  {
      window-&gt;pushCallback('e', [=]()
      {
          // Here the pointer captured changes, causing a segfault later on
      }
  };
  </code></pre>
  
  <p>So now for some context:</p>
  
  <p>The signature for pushCallback looks like this:</p>
  
  <pre><code>void Window::pushCallback(int key, std::function&lt;void()&gt; callback) {}
  </code></pre>
  
  <p>It stores a function to call when the key code denoted by the first argument is called, in this case 'e'.</p>
  
  <p>Menu::onSelect is also a std::function, storing a single function to execute when a menu item is chosen.</p>
  
  <p>Now the obscurity of this problem is that the pointer only changes on the second time stepping through the code. Note that this is an interactive ncurses program. However I have done much testing and have found the pointer changes between the two shown comment lines. Showing that the mutation occurs through capturing the variable in the nested lambdas. I have also made the pointer const in all classes that refer to it.</p>