我试图构建vector的string_view距离Sinitializer_list< const char * >这对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;
}
Run Code Online (Sandbox Code Playgroud)
Clang 也处理代码,好吧,什么给出了?
在这个变量定义中
std::vector< std::string_view > const v { { "Before.", "Afterrrrrr." } };
Run Code Online (Sandbox Code Playgroud)
你不小心使用了这个新的 C++20string_view构造函数:
template<class It, class End>
constexpr basic_string_view(It first, End last);
Run Code Online (Sandbox Code Playgroud)
因此,您只需使用 的开始
作为结束迭代器来构造一个迭代器。 这使得程序具有未定义的行为。string_view"Afterrrrrr."
这将是正确的方法:
std::vector< std::string_view > const v { "Before.", "Afterrrrrr." };
Run Code Online (Sandbox Code Playgroud)