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

66 Views Asked by At

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?

2

There are 2 best solutions below

0
eerorika On BEST ANSWER

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.

0
Owl66 On

You can pass string_view by const ref/ ref but copying string_view is cheap. Pass by value is the most straight forward and recommended way.