Returning a Reference from a Function

Functions can return references, but this can be dangerous. When returning a reference to a variable declared in the called function, unless that variable is declared static, the reference refers to an automatic variable that’s discarded when the function terminates. An attempt to access such a variable yields undefined behavior. References to undefined variables are called dangling references.

Image Common Programming Error 6.9

Returning a reference to an automatic variable in a called function is a logic error. Compilers typically issue a warning when this occurs. For industrial-strength code, always eliminate ...

Get C++ How to Program, Ninth Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.