c++sunstudio

Warning: should not initialize a non-const reference with a temporary


I get the warning from the title on Sun Studio 12.1 with the following snippet:

#include <vector>

std::vector<int> g()
{
  std::vector<int> result;
  result.push_back(5);
  return result;
}

int main()
{
  int b = g()[0];  // <- Warning in this line

  return b;
}

Warning text is:

Warning: should not initialize a non-const reference with a temporary.

While I know that initialising a non-const reference with a temporary is a bad thing, I cannot see how that happens here. I know that [0] returns a reference to the first element of the vector which itself is temporary, but I fail to see what the problem is.

Can somebody explain


Solution

  • This Sun compiler looks very weird, it doesn't seem legitimate at all to me. Ideone has no problem compiling it.

    Regarding the silencing part:

    std::vector<double> const tmp = g();
    int b = tmp[0];
    

    That is, introducing a named variable instead of leaving the temporary floating.

    EDIT:

    As suggested in comments, const-qualifying the return value might help.

    std::vector<double> const g();
    
    int main() {
      int b = g()[0];
      return b;
    }