Re: returning references
Daniel T. wrote:
:: pauldepstein@att.net wrote:
::
::: Below is posted from a link for Stanford students in computer
::: science.
:::
::: QUOTE BEGINS HERE
::: Because of the risk of misuse, some experts recommend never
::: returning a reference from a function or method.
::: QUOTE ENDS HERE
:::
::: I have never heard anyone else say that it is a problem for a
::: function to return a reference.
::
:: "C++ Coding Standards" by Sutter & Alexandrescu. Item 42: Don't
:: give away your internals.
::
:: Don't volunteer too much: Avoid returning handles to internal
:: data managed by your class, so clients won't uncontrollably
:: modify state that your object thinks it owns.
::
:: For context, "handles" above is defined as non-const references,
:: and pointers to non-const data.
::
:: So now you have heard of at least two acknowledged experts who
:: almost state the same thing.
::
::: Are there really experts who object, or is this nothing other than
::: the commonplace observation that reference- returning is a
::: somewhat difficult concept that needs to be learned carefully?
::: (I am just learning about this now.) Assuming programmers have
::: some degree of competence and are able to avoid returning
::: references to locals and so on, what (if anything) are the
::: pitfalls?
::
:: The only valid reference that can be returned from a non-member
:: function is something that either the calling code had access to
:: anyway, or something that is buried in a module.
::
:: The only valid reference that can be returned from a
:: member-function is of something that either the calling code had
:: access to anyway, or something that is private within the class.
::
:: In either case, if you are returning a non-const reference, then
:: the object returned better not have anything to do with the
:: invariant of that class/module or the class/module is asking for
:: trouble (encapsulation is broken.)
But even if you return a const reference to internal data, the
encapsulation is still broken - just a bit less. By returning a
reference, you have promised to somehow keep the referred-to object.
If you return by value, you are more free to change your
implementation later.
Also, we should all note that Sutter & Alexandrescu say "avoid" in
their guidelines, not "never do this". That's an important difference!
Bo Persson