title: Segmentation fault for lambda function in non-static data member initializer
body: <p>I am unsure about a possible GCC bug in initialization of a <code>std::function</code> from a lambda function capturing <code>this</code> in a non-static data member initializer. Is this allowed by the C++ standard or is this UB?</p>
  
  <p>Given the following code:</p>
  
  <pre><code>#include &lt;functional&gt;
  #include &lt;iostream&gt;
  
  template &lt;typename T&gt;
  struct A {
        T x = 0;
        std::function&lt;void(T)&gt; f = [this](T v) { x = v; };
  };
  
  int main() {
        A&lt;int&gt; a;
        a.f(1);
        std::cout &lt;&lt; a.x &lt;&lt; "\n";
  }
  </code></pre>
  
  <p>In my understanding, it should print <code>1</code>. However, when built with GCC 5.4.0 or GCC 6.2.0, <code>a.f(1)</code> emits a segmentation fault, because the captured <code>this</code> pointer is null.</p>
  
  <p>The following alternatives work as I expected:</p>
  
  <ul>
  <li><p>Using constructor initializer list:</p>
  
  <pre><code>template &lt;typename T&gt;
  struct B {
      B() : f([this](T v) { x = v; }) {}
      T x = 0;
      std::function&lt;void(T)&gt; f;
  };
  </code></pre></li>
  <li><p>Without template:</p>
  
  <pre><code>struct C {
      int x = 0;
      std::function&lt;void(int)&gt; f = [this](int v) { x = v; };
  };
  </code></pre></li>
  </ul>
  
  <p>Also, when built with Clang 3.8.0, all three versions behave as I expect, which doesn't mean it is not UB.</p>