You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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
+
constauto& 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:
0 commit comments