Why there isn't a template constructor for std::string_view?

Viewed 636

I was reading the documentation for std::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 introduced this one?

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

In the majority of cases, it would save a call to strlen(). Is there a reason it hasn't been introduced?

1 Answers

The reason is that it's not functionally equivalent

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

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

The strlen thing isn't an issue, since many compilers "know" the meaning of a call to strlen and replace it with a constant, if the argument is constant (after inlining the string_view constructor, the argument becomes a string literal. So std::string_view sv("hello folks") will be efficient).

Related