title: Const reference to member or temporary
body: <p>I have a class that holds data that I expect to use a lot, so I thought it would be best to return a const reference to it. However, given some parameters, I might need to create new data on the fly. I've seen that you can return a temporary to a constant reference like so:</p>
  
  <pre><code>class Foo {
    public:
      Foo() { ... }                    //Initialize data
  
      LARGE_DATA getData(bool param1, bool param2) {
        if (...) {                     // For some crazy function of the parameters
          LARGE_DATA newData = ...;    // Create new data and return it
          return newData
        }
        return data;                   // Usually, will just use the default value
      }
    private:
      LARGE_DATA data;
  };
  
  void bar() {
    Foo f;
    const LARGE_DATA&amp; data = f.getData();
    ...                                // Process data (read-only)
  }
  </code></pre>
  
  <p>but this seems like it would make a copy of <code>data</code>. I would like to do something like this:</p>
  
  <pre><code>class Foo {
    public:
      Foo() { ... }                    //Initialize data
  
      const LARGE_DATA&amp; getData(bool param1, bool param2) {
        if (...) {                     // For some crazy function of the parameters
          LARGE_DATA newData = ...;    // Create new data and return it
          return newData
        }
        return data;                   // Usually, will just use the default value
      }
    private:
      LARGE_DATA data;
  };
  
  void bar() {
    Foo f;
    const LARGE_DATA&amp; data = f.getData();
    ...                                // Process data (read-only)
  }
  </code></pre>
  
  <p>so to avoid unnecessary copies. Visual Studio doesn't complain about this, but g++ does (and probably rightly so). What's the right way to do this?</p>