I understand the motivation for using std::string_view;
it can help avoid unecessary allocations in function arguments.
For example:
The following program will create a std::string
from a string literal.
This causes an undesired dynamic allocation, as we are only interested observing the characters.
#include <iostream>
void* operator new(std::size_t n)
{
std::cout << "[allocating " << n << " bytes]
";
return malloc(n);
}
void observe_string(std::string const& str){}
int main(){
observe_string("hello world"); //prints [allocating 36 bytes]
}
Using string_view
will solve the problem:
#include <iostream>
#include <experimental/string_view>
void* operator new(std::size_t n)
{
std::cout << "[allocating " << n << " bytes]
";
return malloc(n);
}
void observe_string(std::experimental::string_view const& str){
}
int main(){
observe_string("hello world"); //prints nothing
}
This leaves me with a question.
When would I choose std::string by const& instead of string_view for function arguments?
Looking at the interface of std::string_view
, it looks as though I could replace all instances of std::string
that are passed by const&
. Are there any counter examples to this? Is std::string_view
meant to replace std::string const&
for parameter passing?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…