warning: object backing the pointer will be destroyed at the end of the full-expression for std::pair

Viewed 7054

Following code gives the dangling pointer error.

    std::vector<std::pair<std::string, int>> c;
    for (auto& b : c) {
        const auto& [s, i] = b;
        std::string_view v = s.substr(i);
        std::cout << v;
    }

I think that b holds the reference to the std::pair<std::string, int>, so s should be the reference to the string in pair object. Why does this creates the dangling pointer error? What am I missing here? godbolt link: https://godbolt.org/z/4zMvbr

1 Answers

In std::string_view v = s.substr(i);, std::string::substr returns std::string by value, i.e. it returns a temporary std::string. std::string could be converted to std::string_view implicitly, which is constructed from std::string::data(), i.e. the pointer to the underlying array of the temporary std::string. After the full expression, the temporary std::string is destroyed and the pointer held by std::string_view becomes dangling pointer.

It is the programmer's responsibility to ensure that the resulting string view does not outlive the string.

std::string get_string();
int f(std::string_view sv);
 
int x = f(get_string()); // OK
std::string_view sv = get_string(); // Bad: holds a dangling pointer
Related