markmarkmark
markmarkmark

Reputation: 164

Constructing a vector of string_views from an initializer_list

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

Upvotes: 8

Views: 727

Answers (1)

Ted Lyngmo
Ted Lyngmo

Reputation: 117643

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." };

Upvotes: 5

Related Questions