Bewerken

Delen via


Warning C26820

This is a potentially expensive copy operation. Consider using a reference unless a copy is required (p.9)

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

This check covers nonobvious 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.

Remarks

  • 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
    

Example

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