真的没有来自 std::string_view 的 std::string 的显式构造函数吗?

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

本文关键字:std string 构造函数 view 真的      更新时间:2023-10-16

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

这里回答了问题的一部分:

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

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

对有关隐式构造函数的问题的两个答案基本上都指出隐式构造函数会导致内存分配和内存复制,目前尚不清楚程序员是否希望这样做。好的,好吧,使用显式构造函数 - 程序员确实需要分配和复制。为什么不给他/她呢?

tl;大卫:它确实存在。

正如@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<CharT, Traits> 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()
);