Prefer returning by value over returning by const reference for value objects
When returning a const reference, you risk creating a dangling dangling reference:
- You might accidentally return a reference to a local object.
- You might return a reference to an object in an unstable container.
- Example: std::vector invalidates any existing references to elements when it resizes.
When returning a const reference, it also increases cognitive load on the reader, which can be avoided by using the Value Semantics . * F.15: Prefer simple and conventional ways of passing information
Using value semantics is more clear and appropriate for Value Objects, which represent data without identity.
- Return by-reference suggests shared/mutable state and that the specific object instance is important.
- Return by value, value semantics, suggest that the identity (specific instance) is not important.
Return by const reference can be used as optimization if it would be genuinely expensive to copy the object, but be aware of the risks.
class Widget { Point position_; std::string name_; std::vector<LargeData> cache_;
public: // ...
// AVOID - returning references to value objects const Point& get_position() const; const std::string& get_name() const;
// PREFER - return by value for value objects Point get_position() const; std::string get_name() const;
// OK - reference appropriate to avoid expensive copy const std::vector<LargeData>& get_cache() const;}