【问题标题】:Is there really no explicit constructor of std::string from an std::string_view?真的没有来自 std::string_view 的 std::string 的显式构造函数吗?
【发布时间】:2020-10-12 14:55:41
【问题描述】:

一些(很多?)程序员被介绍给std::string_viewstd::string 会问自己:“为什么我可以将后者转换为前者,而反过来却不行?”

这里回答了一部分问题:

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

人们可以喜欢或不喜欢这些原因。但是 - explicit 构造函数呢?我在 cppreference.com 上的 std::string constructors page 上没有看到一个?

关于隐式构造函数的问题的两个答案基本上都表明隐式构造函数会导致内存分配和内存复制,而程序员并不清楚这一点。好的,好吧,使用显式构造函数 - 程序员确实想要分配和复制。为什么不给他/她呢?

【问题讨论】:

标签: c++ c++17 string-view explicit-conversion explicit-constructor


【解决方案1】:

tl;dr:它确实存在。

正如@Barry 和@StoryTeller 所指出的,这个构造函数实际上是存在的——尽管是通过使用模板;您只是没有注意到您链接到的 cppreference 页面上的“细则”:

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

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

t 隐式转换为字符串视图sv,就像std::basic_string_view&lt;CharT, Traits&gt; sv = t;,然后用sv 的内容初始化字符串,就像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()
);

【讨论】:

    猜你喜欢
    • 2022-01-03
    • 1970-01-01
    • 2016-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-16
    • 1970-01-01
    相关资源
    最近更新 更多