将 `std::string` 临时值传递给 `std::string_view` 参数是否安全?

bew*_*x63 4 c++ stdstring string-view c++17

假设我有以下代码:

void some_function(std::string_view view) {
    std::cout << view << '\n';
}

int main() {
    some_function(std::string{"hello, world"}); // ???
}
Run Code Online (Sandbox Code Playgroud)

viewinside会some_function指的string是已被破坏的吗?我很困惑,因为考虑到这段代码:

std::string_view view(std::string{"hello, world"});
Run Code Online (Sandbox Code Playgroud)

产生警告(来自clang++):

warning: object backing the pointer will be destroyed at the end of the full-expression [-Wdangling-gsl]
Run Code Online (Sandbox Code Playgroud)

有什么不同?

(奇怪的是,使用大括号{}而不是方括号()来初始化string_view上面的内容消除了警告。我也不知道为什么会这样。)

需要明确的是,我理解上面的警告( 的string_view寿命比 长string,所以它持有一个悬空指针)。我要问的是为什么传递 astring不会some_function产生相同的警告。

Hol*_*Cat 5

some_function(std::string{"hello, world"});是完全安全的,只要该函数不保留string_view供以后使用。

临时变量std::string在此完整表达式的末尾被销毁(粗略地说,在 this 处;),因此它在函数返回后被销毁。


std::string_view view(std::string{"hello, world"});总是产生一个悬挂的string_view,无论您是否使用(){}。如果括号的选择影响编译器警告,则这是编译器缺陷。