title: Why does this C++ program capturing lambda argument by reference segfault?
body: <p>Here is a minimal program that segfaults with gcc-8.3.0, compiled with <code>-std=c++2a</code>:</p>
  
  <pre><code>struct Command {
      double x;
  };
  
  template &lt;typename T&gt;
  struct AutoBrake {
      AutoBrake(const T&amp; publish) : publish{ publish } {}
      const T&amp; publish;
  };
  
  int main()
  {
      int count{};
      AutoBrake brake{ [&amp;count](const Command&amp;) {
          count += 1;
      } };
  
      brake.publish(Command{ 1.1f });
  }
  </code></pre>
  
  <p>Debugging shows that it crashes when accessing the <code>count</code> reference inside the lambda expression when running <code>brake.publish</code>.</p>
  
  <p>However if the command struct does not contain any fields, the program runs fine:</p>
  
  <pre><code>struct Command {};
  ...
  </code></pre>
  
  <p>AFAIK since Command is taken as a const reference, its lifetime should be extended to the end of main here, so it should not be a dangling reference to a temporary.</p>
  
  <p>Moreover if I do not access count in the lambda the program does not segfault:</p>
  
  <pre><code>...
      int count{};
      AutoBrake brake{ [&amp;count](const Command&amp;) {} };
      brake.publish(Command{});
  ...
  </code></pre>
  
  <p>Finally, if I first store the lambda as a variable it does not segfault:</p>
  
  <pre><code>    int count{};
      auto func = [&amp;count](const Command&amp;) { count += 1; };
      AutoBrake brake{ func };
      brake.publish(Command{});
  </code></pre>