Why is there no template constructor for std :: string_view?

I read the documentation forstd::string_view , and I noticed that these were the constructors:

constexpr basic_string_view() noexcept;
constexpr basic_string_view(const basic_string_view& other) noexcept = default;
constexpr basic_string_view(const CharT* s, size_type count);
constexpr basic_string_view(const CharT* s);

Why didn't they introduce this one?

template<std::size_t n>
constexpr basic_string_view(const CharT(&s)[n]) : basic_string_view(s, n) {}

In most cases, this would save the challenge strlen(). Is there a reason it was not introduced?

+4
source share
1 answer

The reason is that it is not functionally equivalent

char x[255];
sprintf(x, "hello folks");

// oops, sv.size() == 255!
std::string_view sv(x);

The object is strlennot a problem, because many compilers "know" the meaning of the call strlenand replace it with a constant if the argument is constant (after embedding the constructor, the string_viewargument becomes a string literal, therefore it std::string_view sv("hello folks")will be effective).

+2
source

Source: https://habr.com/ru/post/1689408/


All Articles