从 C++17 开始,我们有 std::string_view
, 对连续字符序列的轻量级 View ,可避免不必要的数据复制。现在通常建议使用 std::string_view
来代替 const std::string&
参数。
然而,很快就会发现从 const std::string&
切换到 std::string_view
会破坏使用字符串连接的代码,因为不支持连接 std::string
和 std::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::string
和std::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/