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?

5
  • 3
    There is an explicit constructor of std::string from std::string_view. Commented Jun 22, 2020 at 17:00
  • 2
    stackoverflow.com/a/59424817/3001761 Commented Jun 22, 2020 at 17:01
  • 1
    To be percise there is an explicit c'tor from anything that is convertible to a string_view. Commented Jun 22, 2020 at 17:01
  • Per jonrsharpe, does this answer your question? How to correctly create std::string from a std::string_view? Commented Jun 23, 2020 at 13:05
  • @DavisHerring: While the answer is almost identical, the questions are very different from each other. So, I think these shouldn't be dupes Commented Jun 23, 2020 at 13:35

1 Answer 1

6

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()
);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.