警告:支持指针的对象将在 std::pair 的完整表达式末尾被销毁
warning: object backing the pointer will be destroyed at the end of the full-expression for std::pair
以下代码给出了悬空指针错误。
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;
}
我认为 b
持有对 std::pair<std::string, int>
的引用,因此 s
应该是对对象中的字符串的引用。为什么这会产生悬空指针错误?我在这里错过了什么?神箭 link: https://godbolt.org/z/4zMvbr
在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到std::string_view
,由std::string::data()
构造而成,即指向临时std::string
的底层数组的指针.完整表达式后,临时std::string
被销毁,std::string_view
持有的指针变成悬空指针
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
以下代码给出了悬空指针错误。
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;
}
我认为 b
持有对 std::pair<std::string, int>
的引用,因此 s
应该是对对象中的字符串的引用。为什么这会产生悬空指针错误?我在这里错过了什么?神箭 link: https://godbolt.org/z/4zMvbr
在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到std::string_view
,由std::string::data()
构造而成,即指向临时std::string
的底层数组的指针.完整表达式后,临时std::string
被销毁,std::string_view
持有的指针变成悬空指针
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