title: Avoiding undefined behaviour: passing a temporary to a `std::function` which has a const ref member variable
body: <p>The following example is a simplified version found in production code</p>
  <pre><code>#include &lt;string&gt;
  #include &lt;functional&gt;
  #include &lt;iostream&gt;
  #include &lt;vector&gt;
  
  struct A
  {
      std::string myString = &quot;World&quot;;
  };
  
  struct B
  {
      void operator()() 
      {
          std::cout &lt;&lt; a.myString;
      }
      const A&amp; a;
  };
  
  std::vector&lt;std::function&lt;void()&gt;&gt; v;
  
  void Store(std::function&lt;void()&gt; myFunc)
  {
      v.emplace_back(myFunc);
  }
  
  void Print()
  {
      v[0]();
  }
  
  int main()
  {
      A a; a.myString = &quot;Hello&quot;;
  
      Store(B{a}); // temporary passed with a const-ref of on-the-stack `A`
      Print();
  }
  </code></pre>
  <p>In production code, accessing the string <code>A</code> (i.e. invoking the function through the <code>vector</code> which in turn accesses <code>myString</code> in <code>A</code>) results in a crash. Compiler Explorer seems to be okay with it, however if this behaviour is undefined, the output probably cannot be trusted: <a href="https://godbolt.org/z/cPPKeK9zd" rel="nofollow noreferrer">https://godbolt.org/z/cPPKeK9zd</a></p>
  <p>Assuming this is undefined behaviour and I can only store a <code>const &amp;</code> to <code>A</code>, what can I do in the <code>Store(...)</code> function to issue a compiler error and try to catch the undefined behaviour at compile time.</p>