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
- Why does to compiler complain?
- Is it a legitimate warning?
- If yes, what do I have to change?
- If no, how can I silence it elegantly?
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:
That is, introducing a named variable instead of leaving the temporary floating.
EDIT:
As suggested in comments, const-qualifying the return value might help.