title: Reference in container?
body: <p>I'm having an issue with passing a string as reference to a lambda, when it is in a container. I guess it disappears (goes out of scope) when I call the <code>init()</code> function, but why? And then, why doesn't it disappear when I just pass it as a string reference?</p>
  <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt;
  #include &lt;string&gt;
  
  struct Foo {
    void init(int num, const std::string&amp; txt)
    {
      this-&gt;num = num;
      this-&gt;txt = txt;
    }
  
    int num;
    std::string txt;
  };
  
  int main()
  {
    auto codegen1 = [](std::pair&lt;int, const std::string&amp;&gt; package) -&gt; Foo* {
      auto foo = new Foo;
      foo-&gt;init(package.first, package.second); //here string goes out of scope, exception
      return foo;
    };
  
    auto codegen2 = [](int num, const std::string&amp; txt) -&gt; Foo* {
      auto foo = new Foo;
      foo-&gt;init(num, txt);
      return foo;
    };
  
    auto foo = codegen1({3, &quot;text&quot;});
    auto foo2 = codegen2(3, &quot;text&quot;);
    std::cout &lt;&lt; foo-&gt;txt;
  } 
  </code></pre>
  <p>I know the way to go would be to use <code>const std::pair&lt;int, std::string&gt;&amp;</code>, but I want to understand why this approach doesn't work.</p>