Cppcheck is a static analyzer for C and C++. With C++ code I sometimes see the check returnByReference
warning that
Function 'foo()' should return member 'bar' by const reference.
Why should I return members by const reference? Why are members different from local variables? What are the pros and cons of changing this?
Why should I return members by const reference?
From the Cppcheck 2.14.0 documentation:
returnByReference: warns when a large class member is returned by value from a getter function
Pros: not passing around a large object by value. A large object can be relatively expensive to copy in memory. For some situations, returning a large object is appropriate, and other situations it may be an optimization opportunity to consider by returning a const reference.
Cons: tight coupling to the internal implementation details. This can be an issue if the caller of the getter is not anticipating that the const reference might be to a mutating object while that caller is holding onto a const reference to the member variable. Or if the held const reference could become a dangling reference by the owning object.
From wohlstad's comment:
Why are members different from local variables?
Local variables lifetime ends when the method returns (so a reference to them will become dangling), unlike members which live as long as the class instance lives.