c++stdpass-by-valuestring-viewpass-by-const-reference

Why does string_view::operator== accepts parameters by value


I was reading source code of string_view, and found that operator== accepts parameters by value.

template<typename _CharT, typename _Traits>
    constexpr bool
    operator==(basic_string_view<_CharT, _Traits> __x,
               basic_string_view<_CharT, _Traits> __y) noexcept
    { return __x.size() == __y.size() && __x.compare(__y) == 0; }

Why does it accepts parameters by value, not by const reference?


Solution

  • Why does string_view::operator== accepts parameters by value

    Because that is the recommended way to pass arguments that are not modified, and are cheap to copy.

    There is no need to pay the cost of indirection introduced by the reference - that said, the function would in most cases be expanded inline in which case it wouldn't really matter.

    Isn't passing by reference cheaper?

    In general: it depends. In case of string view: Probably not.