我了解使用 std::string_view 的动机;
它可以帮助避免函数参数中不必要的分配。
例如:
下面的程序将创建一个 std::string
从字符串文字。
这会导致不希望的动态分配,因为我们只对观察字符感兴趣。
#include <iostream>
void* operator new(std::size_t n)
{
std::cout << "[allocating " << n << " bytes]\n";
return malloc(n);
}
void observe_string(std::string const& str){}
int main(){
observe_string("hello world"); //prints [allocating 36 bytes]
}
使用
string_view
将解决问题:#include <iostream>
#include <experimental/string_view>
void* operator new(std::size_t n)
{
std::cout << "[allocating " << n << " bytes]\n";
return malloc(n);
}
void observe_string(std::experimental::string_view const& str){
}
int main(){
observe_string("hello world"); //prints nothing
}
这给我留下了一个问题。
我什么时候会通过 const& 选择 std::string 而不是 string_view 作为函数参数?
查看
std::string_view
的界面,看起来我可以替换 std::string
的所有实例由 const&
传递的.有什么反例吗?是 std::string_view
意在取代 std::string const&
用于参数传递?
最佳答案
When would I choose
std::string
byconst&
instead ofstring_view
for function arguments?
你需要一个以空字符结尾的字符串吗?如果是这样,那么您应该使用
std::string const&
这为您提供了保证。 string_view
不是 - 它只是一个范围 const char
.如果您不需要以空字符结尾的字符串,并且不需要取得数据的所有权,那么您应该使用
string_view
.如果您确实需要获得数据的所有权,则可能是 string
按值优于 string_view
.
关于c++ - 我什么时候通过 const& std::string 而不是 std::string_view ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59097859/