mgehre / llvm-project

The home of the clang-based implementation of lifetime safety warnings.
39 stars 4 forks source link

std::string& dangling after append? #53

Closed mgehre closed 5 years ago

mgehre commented 5 years ago

On

#include <string>
#include <vector>

void f(std::vector<std::string> v) {
    for(std::string &r: v) {
        r += "";
        r.back();
    }
}

we warn

<source>:7:9: warning: dereferencing a dangling pointer [-Wlifetime]
        r.back();

<source>:6:9: note: modified here
        r += "";

but r += "" modifies the string, not the reference, so the reference does not dangle.

https://godbolt.org/z/wbvyfd

fyi @Xazax-hun

Xazax-hun commented 5 years ago

A slightly smaller repro (eliminated the loop):

#include <string>
#include <vector>

void f(std::vector<std::string> v) {
   std::string &r = v[0];
   r += "aa";
   r.back();
}