CppCoreGuidelines
CppCoreGuidelines copied to clipboard
Rule Con.1 can lead to inefficient codegen
Enforced application of rule Con.1 can have detrimental effects on performance. It can force a copy (more expensive operation in general) when a move (a cheaper operation in general) would have been performed for local variables that are returned. See demo on godbolt link: https://godbolt.org/z/oTcK49EY3
Programmers, in general, don't think of a return statement as a modifying operation they are performing on the operand since the move operation (when it happens) is pretty invisible, as is the performance hit.
Suggestion: Augment the exception section to also cover local variables that are returned.
Editors call: We think C++26 ought to treat return local; as a non-const rvalue (not just an rvalue). In the meantime, we should add a Note or Exception to this guideline to say that a local variable that is cheaper to move than to copy and that is returned by value should not be declared const. Please create a PR with proposed text. Thanks!