Compiling my code with gcc 13.2 and -Wdangling-reference
I was surprised that in this simple scenario (godbolt):
#include <vector>
#include <string>
std::string& add_variable(std::vector<std::string>& vars, const std::string& var)
{
vars.push_back( var );
return vars.back();
}
int main()
{
std::vector<std::string> vars;
const std::string& var = add_variable(vars, "name");
}
The compiler warns that:
<source>:13:41: warning: possibly dangling reference to a temporary [-Wdangling-reference]
13 | const std::string& var = add_variable(vars, "name");
| ^~~
<source>:13:59: note: the temporary was destroyed at the end of the full expression 'add_variable(vars, std::__cxx11::basic_string<char>(((const char*)"name"), std::allocator<char>()))'
13 | const std::string& var = add_variable(vars, "name");
|
Is this a false positive or there's something big I'm missing here?
Indeed, it looks like a false positive. var
is referencing the std::string
in your vector<string>
which is still very much alive after the full expression.