从C++ 1z开始,我们可以std::string_view轻松地查看连续的字符序列,避免不必要的数据复制.const std::string&现在经常建议使用,而不是使用参数std::string_view.
但是,很快就会发现切换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)
Run Code Online (Sandbox Code Playgroud)
为什么不支持连接std::string和std::string_view标准?
通过string_view使用C ++ 17,我们得到了一种便宜的方法,该方法将std::string和传递char*给不占用字符串所有权并避免制作临时副本的函数。通过使用std::string按值传递,std::move我们可以为r值和l值引用显式快速地传递字符串所有权。
我的问题是:const std::string&在新的C ++标准中用作任何函数参数有什么好处?
我一直在研究该std::string_view库,并且一直在考虑更改我一直在努力使用的代码库std::string_view。但是,在我阅读过的许多主题中,有关何时何地使用std::string_view而不是的主题const std::string &。我已经看到许多答案说:“何时不需要以null结尾的字符串。” 因此,当我开始在网上搜索“何时需要以null结尾的字符串?”时,在这个问题上,我还没有真正有用的答案。
我可以想到一个外部库的示例,您需要链接到该外部库std::string。在那种情况下,您将需要一个以null结尾的字符串,因为该库需要它。我猜另一个例子是,如果您需要修改字符串本身,但是const &如果我们需要修改它,那么我们就不会通过。
那么什么时候需要使用以null结尾的字符串?
我看过的链接:
我更喜欢const std::string &总是在我需要打std::string秒。但是最近,我突然发现根本不需要使用它const std::string &。该std::string_view会做的更好为只读字符串,并只std::string用move将否则(设置字符串字段等等)做的更好。
// Read-only string example
bool foo(std::string_view bar) {
return bar == "baz";
}
Run Code Online (Sandbox Code Playgroud)
// Non read-only string example
void MyClass::foo(std::string bar) {
this->baz = std::move(bar);
}
Run Code Online (Sandbox Code Playgroud)
在以上两种情况下,const std::string &不是最优的!
因此,我决定删除所有,const std::string &并用其中之一替换它们。所以我的问题是:
const std::string &会更好吗?const std::string &吗?谢谢。