Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 387
Jaebum Avatar asked Nov 03 '20 05:11

Jaebum


People also ask

Why is the pointer dangling in c26815?

Table of contents Warning C26815 The pointer is dangling because it points at a temporary instance that was destroyed. (ES.65) Article 08/03/2021 2 minutes to read

What does warning c26815 mean in C++?

Learn more about: Warning C26815 The pointer is dangling because it points at a temporary instance that was destroyed. (ES.65) c++ c26815 | Microsoft Docs Skip to main content This browser is no longer supported. Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Why is my pointer dangling CMD?

Warning C26815 The pointer is dangling because it points at a temporary instance that was destroyed. (ES.65) There is a dangling pointer that is the result of an unnamed temporary that has been destroyed. These warnings can be fixed by extending the lifetime of the temporary object.


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
like image 194
songyuanyao Avatar answered Sep 17 '22 09:09

songyuanyao