Are the days of passing const std::string & as a parameter over?

后端 未结 13 1798

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

相关标签:
13条回答
  • 2020-11-22 17:33

    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.

    0 讨论(0)
提交回复
热议问题