From 56e5b42eeecf5d4d7db55a0d3d44d9df3f4b52ab Mon Sep 17 00:00:00 2001 From: bgloyer <36457894+bgloyer@users.noreply.github.com> Date: Thu, 12 Oct 2023 13:02:28 -0700 Subject: [PATCH] Con.1 Issue #1905 Return local const (#2114) * Con.1 const return * minor --- CppCoreGuidelines.md | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/CppCoreGuidelines.md b/CppCoreGuidelines.md index 57f0ad3..4a2b6e1 100644 --- a/CppCoreGuidelines.md +++ b/CppCoreGuidelines.md @@ -16859,19 +16859,28 @@ Prevents accidental or hard-to-notice change of value. for (int i : c) cout << i << '\n'; // BAD: just reading -##### Exception +##### Exceptions + +A local variable that is returned by value and is cheaper to move than copy should not be declared `const` +because it can force an unnecessary copy. + + std::vector f(int i) + { + std::vector v{ i, i, i }; // const not needed + return v; + } Function parameters passed by value are rarely mutated, but also rarely declared `const`. To avoid confusion and lots of false positives, don't enforce this rule for function parameters. - void f(const char* const p); // pedantic void g(const int i) { ... } // pedantic Note that a function parameter is a local variable so changes to it are local. ##### Enforcement -* Flag non-`const` variables that are not modified (except for parameters to avoid many false positives) +* Flag non-`const` variables that are not modified (except for parameters to avoid many false positives +and returned local variables) ### Con.2: By default, make member functions `const`