Skip to main content

Item 28: Avoid returning "handles" to object internals

Concept​

Returning references, pointers, or iterators to internal data violates encapsulation and can lead to dangling handles. Even returning const references doesn't prevent dangling if the object is a temporary.

Code Example​

class Rectangle {
public:
// Bad: exposes internals
Point& upperLeft() const { return pData->ulhc; }

// Better but still risky with temporaries
const Point& upperLeft() const { return pData->ulhc; }
};

Full source code

Things to Remember​

  • Avoid returning handles (references, pointers, or iterators) to object internals. It increases encapsulation, helps const member functions act const, and minimizes dangling handles.
  • Item 3 — Use const whenever possible
  • Item 22 — Declare data members private