c++ - 为什么不支持连接 std::string 和 std::string_view?

标签 c++ string c++17 string-view

从 C++17 开始,我们有 std::string_view , 对连续字符序列的轻量级 View ,可避免不必要的数据复制。现在通常建议使用 std::string_view 来代替 const std::string& 参数。

然而,很快就会发现从 const std::string& 切换到 std::string_view 会破坏使用字符串连接的代码,因为不支持连接 std::stringstd::string_view:

std::string{"abc"} + std::string_view{"def"}; // ill-formed (fails to compile)
std::string_view{"abc"} + std::string{"def"}; // ill-formed (fails to compile)

为什么标准中不支持std::stringstd::string_view拼接?

最佳答案

原因在 n3512 string_ref: a non-owning reference to a string, revision 2 中给出。杰弗里·亚斯金:

I also omitted operator+(basic_string, basic_string_ref) because LLVM returns a lightweight object from this overload and only performs the concatenation lazily. If we define this overload, we'll have a hard time introducing that lightweight concatenation later.

后来在 std-proposals 上提出了建议将这些运算符重载添加到标准的邮件列表。

关于c++ - 为什么不支持连接 std::string 和 std::string_view?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44636549/

相关文章:

c++ - 无法在应用商店的沙盒 OSX 应用中使用 libproc

string - BSTR 和字符串

java - 在java中将单词分成两个分区

C++ std::filesystem::filesystem_error 异常试图读取系统卷信息等

C++:在类内、类外应用枚举

c++ - 具有默认参数值的函数中的默认对象值

c++ - 为什么操作系统不拒绝为该程序分配内存?

android - 将巨大的字符串从 native 传递到 java - 内存不足错误

c++ - 类模板特化推导是否应该考虑推导指导参数初始化?

c++ - std::reduce 似乎将结果转换为整数