title: reference in member class scope
body: <p>I came across this code, it does not work properly for the input 'bad', I know the reason, but I don´t understand it. I guess the problem is when the object is created. Could you guys explain it to me?</p>
  
  <p>--Edited. Sorry, I put the &amp; where it wasn´t.
  const std::string&amp; _badString; --> Here is where the problem is. If you run it with the argument 'bad', the exception is caught, but when printing the string, which should be 'bad', it only prints garbage.</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;string&gt;
  
  namespace
  {
      const std::string bad = "bad";
  }
  
  class MyException
  {
      const std::string&amp; _badString;
  
  public:
      MyException(const std::string&amp; s):
      _badString(s)
      {
      }
  
      auto badString() const
      {
          return _badString;
      }
  };
  
  
  template&lt;typename Arg&gt;
  void interpretArg(Arg arg)
  {
      if (arg == bad)
      {
           throw MyException(arg);
      }
  }
  
  int main(int argc, char** argv)
  {
      for (int i = 0; i &lt; argc; ++i)
      {
          try
          {
              interpretArg(argv[i]);
          }
          catch(const MyException&amp; e)
          {
              std::cerr &lt;&lt; "badString: " &lt;&lt; e.badString() &lt;&lt; std::endl;
          }
      }
  }
  </code></pre>