真的没有std :: string_view的std :: string的显式构造函数吗? [英] Is there really no explicit constructor of std::string from an std::string_view?

查看:411
本文介绍了真的没有std :: string_view的std :: string的显式构造函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

同时介绍了std::string_viewstd::string的一些(很多?)程序员问自己:为什么我可以将后者转换为前者,而不是相反?"

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:

为什么没有从std :: string_view到std :: string的隐式转换?

并且可以喜欢或不喜欢原因.但是- explicit 构造函数呢?我没有在 std::string构造函数页面上看到一个cppreference.com?

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?

推荐答案

tl; dr:实际上确实存在.

正如@Barry和@StoryTeller指出的那样,此构造函数实际上存在-尽管通过使用模板来实现;您只是没有注意到精美图片"在您链接到的cppreference页面上:

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

这将从std::string_view构造一个std::string.为什么?因为它是什么:

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

就像通过std::basic_string_view<CharT, Traits> sv = t;一样,将t转换为字符串视图sv,然后像通过std::basic_string(sv.data(), sv.size(), alloc)一样,将sv的内容初始化为字符串.

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

对于T = std::string_view的具体情况:

template <>
explicit constexpr basic_string<std::string_view>(
    const std::string_view& t,
    const Allocator& alloc = Allocator()
);

这篇关于真的没有std :: string_view的std :: string的显式构造函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆