I'm trying to construct a vector
of string_view
s from an initializer_list< const char * >
which worked okay on GCC 9, but after updating to GCC 10 it crashes during runtime.
#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 also handles the code okay, what gives?
Link: https://godbolt.org/z/6s1c61
In this variable definition
std::vector< std::string_view > const v { { "Before.", "Afterrrrrr." } };
you accidentally used this new C++20 string_view
constructor:
template<class It, class End>
constexpr basic_string_view(It first, End last);
So, you only construct one string_view
using the start of "Afterrrrrr."
as the end iterator. This makes the program have undefined behavior.
This would be the proper way:
std::vector< std::string_view > const v { "Before.", "Afterrrrrr." };
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