Initializing string Members from string_view
We'll continue our analysis of the example from the last chapter, this time using std::string_view instead of std::string.
We'll cover the following...
We'll cover the following...
Last time, we were left with this code:
Since the introduction of move semantics in C++11, it’s usually better, and safer to pass string as a value and then move from it.
For example:
Now we have the following results:
For std::string:
u1- one allocation - for the input argument and then one move into themName. It’s better than withconst std::string&where we got two memory allocations in that case. And similar to the string_view approach.u2- one allocation - we have to copy the value into the argument, and then we can move from it.u3- no allocations, only two move operations - that’s better than withstring_viewandconst string&!
When you pass std::string by value not only is the code simpler, there’s also no need to write separate overloads for rvalue references.
See the full code sample:
The approach with passing by value is consistent with item 41 - “Consider pass by value for copyable parameters that are cheap to move and always copied” from Effective Modern C++ by Scott ...