Warning C26820

Assigning by value when a const-reference would suffice, use const auto& instead (p.9).

For more information, see P.9: Don't waste time or space in the C++ Core Guidelines.

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.


  • 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.

  • This warning isn't raised when the variable gets mutated, as marking it auto& would introduce side-effects to the mutation.

  • This warning isn't raised when the reference comes from a temporary object, because that results in a dangling reference. For example:

    std::optional<int> TryGetNumber();
    const auto& val = TryGetNumber().value();
    val++; // Temporary from TryGetNumber() is destroyed and val is now dangling


This sample shows a variable definition that makes a potentially expensive copy when assigned a reference:

const Object& MyClass::getRef() { ... }
auto ref = myclass.getRef(); // C26820 (`ref` takes a copy of the returned object)

To resolve this issue, declare the variable by using const auto& instead:

const Object& MyClass::getRef() { ... }
const auto& ref = myclass.getRef(); // OK