Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is g++ -Wdangling-reference warning justified in this case?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading