Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructing a vector of string_views from an initializer_list

Tags:

c++

gcc

c++20

I'm trying to construct a vector of string_views 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

like image 543
markmarkmark Avatar asked Oct 06 '20 07:10

markmarkmark


1 Answers

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." };
like image 120
Ted Lyngmo Avatar answered Nov 11 '22 02:11

Ted Lyngmo