Skip to content

Commit dfa0674

Browse files
authored
Merge pull request #2798 from corob-msft/dmitrykobets-c26820
Document new rule C26820
2 parents 44ebf57 + d5ed3ca commit dfa0674

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

docs/code-quality/c26820.md

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
---
2+
title: C26820
3+
description: "Reference for Microsoft C++ Code Analysis warning C26820 in Visual Studio."
4+
ms.date: 04/07/2020
5+
f1_keywords: ["C26820"]
6+
helpviewer_keywords: ["C26820"]
7+
---
8+
# C26820
9+
10+
> Assigning by value when a const-reference would suffice, use const T& instead (p.9).
11+
12+
For more information, see [P.9: Don't waste time or space](https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#p9-dont-waste-time-or-space) in the C++ Core Guidelines.
13+
14+
This check covers non-obvious and easy-to-miss behavior when assigning a reference to a variable marked `auto`. The type of the `auto` variable is resolved to a value rather than a reference, and an implicit copy is made.
15+
16+
## Remarks
17+
18+
- This warning isn't raised for scalars, smart pointers, or views. It's also not raised for types whose size isn't more than twice the platform-dependent pointer size.
19+
- This warning isn't raised when the variable gets mutated, as marking it `auto&` would introduce side-effects to the mutation.
20+
- This warning isn't raised when the reference comes from a temporary object, because that results in a dangling reference. For example:
21+
22+
```cpp
23+
std::optional<int> TryGetNumber();
24+
...
25+
const auto& val = TryGetNumber().value();
26+
val++; // Temporary from TryGetNumber() is destroyed and val is now dangling
27+
```
28+
29+
## Example
30+
31+
This sample shows a variable definition that makes a potentially expensive copy when assigned a reference:
32+
33+
```cpp
34+
MyClass& ref = ...;
35+
auto var = ref; // C26820 (`var` takes a copy of the object referred to by `ref`)
36+
```
37+
38+
To resolve this issue, declare the variable by using `const auto&` instead:
39+
40+
```cpp
41+
MyClass& ref = ...;
42+
const auto& var = ref; // OK
43+
```

docs/code-quality/toc.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -570,6 +570,8 @@
570570
href: c26810.md
571571
- name: C26811
572572
href: c26811.md
573+
- name: C26820
574+
href: c26820.md
573575
- name: C28020
574576
href: c28020.md
575577
- name: C28021

0 commit comments

Comments
 (0)