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
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
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With