简体   繁体   中英

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

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?

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM