Three reasons to pass std::string_view by value--Arthur O’Dwyer

You should.

Three reasons to pass std::string_view by value

by Arthur O’Dwyer

From the article:

It is idiomatic to pass std::string_view by value. Let’s see why.

First, a little background recap. In C++, everything defaults to pass-by-value; when you say Widget w you actually get a whole new Widget object. But copying big things can be expensive. So we introduce “pass-by-const-reference” as an optimization of “pass-by-value,” and we tell people to pass big and/or expensive things like std::string by const reference instead of by value.

But for small cheap things — int, char*, std::pair<int, int>, std::span<Widget> — we continue to prefer the sensible default behavior of pass-by-value.

Pass-by-value has at least three performance benefits over pass-by-(const)-reference. I’ll illustrate all three of them via string_view...

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.