0

Some (many?) programmers who are introduced to both std::string_view and std::string ask themselves: "Why can I convert the latter into the former, but not the other way around?"

One part of the question is answered here:

Why is there no implicit conversion from std::string_view to std::string?

and one can like or dislike the reasons. However - what about an explicit constructor? I don't see one on the std::string constructors page on cppreference.com?

Both answers to questions regarding implicit constructors essentially state that an implicit constructor would cause an memory allocation and memory copy, which it's not clear the programmer desires. Ok, well, with an explicit constructor - the programmer does want the allocation and the copy. Why not give it to him/her?

einpoklum
  • 118,144
  • 57
  • 340
  • 684

1 Answers1

4

tl;dr: It actually does exist.

As @Barry and @StoryTeller indicate, this constructor actually exists - albeit through the use of templates; you're just failing to notice the "fine print" on the cppreference page you linked to:

template < class T >
explicit constexpr basic_string(
    const T& t,
    const Allocator& alloc = Allocator()
);

this will construct an std::string from a std::string_view. Why? Because what it:

Implicitly converts t to a string view sv as if by std::basic_string_view<CharT, Traits> sv = t;, then initializes the string with the contents of sv, as if by std::basic_string(sv.data(), sv.size(), alloc).

For the specific case of T = std::string_view:

template <>
explicit constexpr basic_string<std::string_view>(
    const std::string_view& t,
    const Allocator& alloc = Allocator()
);
einpoklum
  • 118,144
  • 57
  • 340
  • 684