I heard a recent talk by Herb Sutter who suggested that the reasons to pass std::vector
and std::string
by const &
are largely gon
Almost.
In C++17, we have basic_string_view<?>
, which brings us down to basically one narrow use case for std::string const&
parameters.
The existence of move semantics has eliminated one use case for std::string const&
-- if you are planning on storing the parameter, taking a std::string
by value is more optimal, as you can move
out of the parameter.
If someone called your function with a raw C "string"
this means only one std::string
buffer is ever allocated, as opposed to two in the std::string const&
case.
However, if you don't intend to make a copy, taking by std::string const&
is still useful in C++14.
With std::string_view
, so long as you aren't passing said string to an API that expects C-style '\0'
-terminated character buffers, you can more efficiently get std::string
like functionality without risking any allocation. A raw C string can even be turned into a std::string_view
without any allocation or character copying.
At that point, the use for std::string const&
is when you aren't copying the data wholesale, and are going to pass it on to a C-style API that expects a null terminated buffer, and you need the higher level string functions that std::string
provides. In practice, this is a rare set of requirements.