[英]Constructing a vector of string_views from an initializer_list
我正在嘗試從initializer_list< const char * >
構造一個string_view
vector
,它在 GCC 9 上工作正常,但在更新到 GCC 10 后,它在運行時崩潰。
#include <vector>
#include <string_view>
#include <cstdio>
int main()
{
std::vector< std::string_view > const v { { "Before.", "Afterrrrrr." } };
printf( "%s %zu\n", v[0].data(), v[0].length() );
printf( "%s %zu\n", v[1].data(), v[1].length() );
return 0;
}
Clang 也處理代碼,好吧,什么給出了?
鏈接: https : //godbolt.org/z/6s1c61
在這個變量定義中
std::vector< std::string_view > const v { { "Before.", "Afterrrrrr." } };
你不小心使用了這個新的 C++20 string_view
構造函數:
template<class It, class End>
constexpr basic_string_view(It first, End last);
所以,你只構造一個string_view
使用的開始"Afterrrrrr."
作為結束迭代器。 這使得程序具有未定義的行為。
這將是正確的方法:
std::vector< std::string_view > const v { "Before.", "Afterrrrrr." };
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.