2 ms·
Most of the author's points are well-taken. But not all of them... for example: auto plus(std::string s, std::string t) { return s + t; } > The above code i
by einpoklum 5y ago
Most of the author's points are well-taken. But not all of them... for example:
auto plus(std::string s, std::string t) { return s + t; }
> The above code is bad because it makes unnecessary copies
Maybe, maybe not. A compiler may inline it (although, TBH, even regardless of parameter constness, std::string is very copy-prone in general.)
> What we mean to write is:
auto plus(const std::string& s, const std::string& t)
Not quite. That is, this implies we don't want to take rvalues (e.g. temporary strings). It will work with rvalues, but we might be making copies for them.
When you think about it, we don't even need the actual string class; we only need access to the characters. So...
auto plus( std::string_view s, std::string_view t)
(this is C++17; before that, try: https://github.com/martinmoene/string-view-lite https://github.com/martinmoene/string-view-lite )
Also, why use the `auto` return type? I avoid it unless it hides some complex monstrosity, or it's a template where it's difficult to figure out. Here I would write:
std::string plus( std::string_view s, std::string_view t)
> In function signatures: the ugly is the bad
This is... a good principle, in thoery, but in practice, not always :-)
But this principle is part of why we don't want to talk about const &'s and just pass things by value if we can.