title: Return a reference from a function that takes it as a parameter
body: <p>I have a class that does this, conceptually. Note that the underlying data types are more complex in the real application. This is just for simplification:</p>
  
  <pre class="lang-cpp prettyprint-override"><code>class A
  {
    private:
    std::map&lt;std::string, int&gt; database;
  
    public:
    bool knowsValue(std::string string_id);  // Returns true if string_id is in database
    const int&amp; getValueA(std::string string_id);  // Returns reference to int mapped to string_id in database
  }
  </code></pre>
  
  <p>Because calling getValueA for an unknown <code>string_id</code> causes an error, both commands are usually called together:</p>
  
  <pre class="lang-cpp prettyprint-override"><code>if obj.knowsValue(string_id)
    int val = obj.getValueA(string_id)
  else
    std::cout &lt;&lt; "Value does not exist in database";
  </code></pre>
  
  <p>Because this requires two subsequent <code>find</code> operations on the database object, I made this function <code>bool getValueB(std::string string_id, int&amp; val)</code>, which returns true if <code>string_id</code> is in the database, and assigns the mapped value to <code>val</code>.</p>
  
  <p>The content of the two <code>getValue</code> functions is almost identical, so I wanted to reuse <code>getValueB</code> in <code>getValueA</code>. This is where I am out of my depth, with this attempt:</p>
  
  <pre class="lang-cpp prettyprint-override"><code>const int&amp; getValueA2(std::string string_id)
  {
    static int val_tmp;  // If not static, this object is deleted after the function call and the reference becomes invalid
    if (getValueB(string_id, val_tmp))
      return static_cast&lt;const int&amp;&gt;(val_tmp);
    else
      return static_cast&lt;const int&amp;&gt;(0);
  }
  </code></pre>
  
  <p>Obviously the <code>static</code> keyword is inappropriate here, because the value should not be shared between functions. Also, the fact that the reference is not <code>const</code> in <code>getValueB</code> is also suboptimal.</p>
  
  <p>My questions:</p>
  
  <ul>
  <li>What is the right way to write <code>getValueA2</code>, which tries to return a reference that it obtains in a parameter? The intermediate <code>val_tmp</code> seems icky.</li>
  <li>Can the reference be <code>const</code> in this structure at all?</li>
  </ul>
  
  <p>I am leaning towards changing <code>getValueB</code> to <code>const int&amp; getValueB(std::string string_id, const bool value_exists_in_db)</code> to untangle this mess, but I would be interested in finding out what is possible and where I went wrong.</p>
  
  <hr>
  
  <p>edit: Note that the declaration of <code>const int&amp; getValueA(std::string string_id)</code> should not change, ideally, to avoid changes in the rest of the codebase.</p>