8

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

0

1 Answer 1

5

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." };
1
  • 3
    The problem also consequetly disappears with -std=c++17. The constructor was added into libstdc++ in this commit, which implements P1391R4. Commented Oct 6, 2020 at 8:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.