真的没有来自 std::string_view 的 std::string 的显式构造函数吗?
Is there really no explicit constructor of std::string from an std::string_view?
一些(很多?(程序员被介绍给std::string_view
和std::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()
);
相关文章:
- cppcheck在const std::string[]上引发警告
- 将std::string传递给WriteConsole API
- 为std::string的某个索引赋值
- 使用 std::string () const 函数启动线程或未来
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 如何更改大小(std::string)
- std::string 的对象真的可以移动吗?
- SegFault 同时使用 std::string::operator+= 和函数作为参数
- 无法从 std::string 中提取C++ Unicode 符号
- std::string 构造函数如何处理固定大小的 char[]?
- 真的没有来自 std::string_view 的 std::string 的显式构造函数吗?
- 将C++ std::string 转换为 UTF-16-LE 编码的字符串
- 重载 + 自己的类和 std::string 的运算符
- 如何使用 std::string 作为 QHash 的键?
- 将日语 wstring 转换为 std::string
- 可以从std::string继承以提供类型一致性吗
- 构造函数采用std::string_view与std::string并移动
- 在共享缓冲区内存中创建 ::std::string 对象
- std::string.size() 未知行为
- Valgrind 在 std::string::swap 中报告 SIGILL