1

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?

Jouni
  • 321
  • 1
  • 8
  • 5
    A `stringview` was made to be a cheap, copyable view into a string. – NathanOliver Jun 03 '20 at 13:49
  • 1
    Same general principle talked about here https://stackoverflow.com/questions/27256377/c-view-types-pass-by-const-or-by-value – StoryTeller - Unslander Monica Jun 03 '20 at 13:50
  • @NathanOliver Isn't passing by reference cheaper? – Jouni Jun 03 '20 at 13:51
  • 1
    @Jouny In a function that can be easily inlined, like this, there is unlikely to be any difference. In a function that can't be inlined, using a reference requires slightly less memory, but adds a level of indirection (the classic size vs speed trade-off). Since these view objects are already basically a subset-reference of another string, you would have a reference to a reference. – cdhowie Jun 03 '20 at 13:55
  • @Jouny Maybe. I'd be surprised if you notice a difference in an optimized build though. – NathanOliver Jun 03 '20 at 13:57
  • possible (likely?) duplicate of [C++ view types: pass by const& or by value?](https://stackoverflow.com/questions/27256377/c-view-types-pass-by-const-or-by-value) – underscore_d Jun 03 '20 at 14:07

2 Answers2

2

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.

eerorika
  • 232,697
  • 12
  • 197
  • 326
0

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.

Owl66
  • 147
  • 12