Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

c++ - Is there really no explicit constructor of std::string from an std::string_view?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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()
);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...