4 ms·
That guidance isn't correct in the C++11 New World Order. For maximum performance, you must think about move semantics. Simply saying const X& everywhere will i
by StephanTLavavej 10y ago
That guidance isn't correct in the C++11 New World Order. For maximum performance, you must think about move semantics. Simply saying const X& everywhere will inhibit move semantics (can't move from const, can't move from lvalues, especially can't move from lvalue-ref-to-const).
For example, suppose you're writing a FancyAppend() function, that will return "LhsString, RhsString". Following your guidance, the signature would be "string FancyAppend(const string&, const string&)". While that definitely avoids copying the inputs, it is not optimal. Providing additional overloads for string&& parameters can be more efficient (if at least one input is a modifiable rvalue, it can be appended to in-place, which can avoid additional memory allocation if it happens to have sufficient capacity; for repeated appends, this can avoid quadratic copying of elements). Indeed, this is what string's operator+() does.
Note that working with rvalue references does require more understanding. For example, the signature "string&& BadAppend(string&&, const string&)" is a severe error (one that the Standardization Committee made early on, and corrected before shipping).
- AstralStorm 10y agoAnd if you support both const arguments, maybe whole or part of the function can be declared constexpr. (or pure in C++17 or is it even 14)
- StephanTLavavej 10y agoThere's no such thing as "pure" in Standard C++ yet, even the C++17 Working Paper.
- AstralStorm 10y agoIsn't that specified as one of the attributes? Maybe it's just a common extension.