What about returning const references?

Sometimes, newer developers return const references just to be symmetric with the well-known best practice of taking class type arguments by const reference. However, this can cause a few issues.

What is the problem?

The problem with returning const references is that the returned object has to outlive the caller. At least it has to live as long as the caller exists.

void f() {
  MyObject o;
  const auto& aRef = o.getSomethingConstRef();
  aRef.doSomething(); // will this work?
}

Will that work? It depends.

If MyObject::getSomethingConstRef() returns a const reference of a local variable, it will not work. It is because local variables are destroyed immediately when the program moves beyond the scope of the function.

Get hands-on with 1200+ tech skills courses.