mirror of
https://github.com/isocpp/CppCoreGuidelines.git
synced 2025-12-17 12:44:42 +03:00
* Con.1 const return * minor
This commit is contained in:
@@ -16859,19 +16859,28 @@ Prevents accidental or hard-to-notice change of value.
|
|||||||
|
|
||||||
for (int i : c) cout << i << '\n'; // BAD: just reading
|
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<int> f(int i)
|
||||||
|
{
|
||||||
|
std::vector<int> v{ i, i, i }; // const not needed
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
|
||||||
Function parameters passed by value are rarely mutated, but also rarely declared `const`.
|
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.
|
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
|
void g(const int i) { ... } // pedantic
|
||||||
|
|
||||||
Note that a function parameter is a local variable so changes to it are local.
|
Note that a function parameter is a local variable so changes to it are local.
|
||||||
|
|
||||||
##### Enforcement
|
##### 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)
|
||||||
|
|
||||||
### <a name="Rconst-fct"></a>Con.2: By default, make member functions `const`
|
### <a name="Rconst-fct"></a>Con.2: By default, make member functions `const`
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user