Is there ANY EVER reason why i would return an object or variable by reference? to me this doesn't make sense and is very bad.

Recommended Answers

All 6 Replies

you'll end up with hell of a debugging time.
:) contaz you got the job, you walk in a part where demons and monsters are willingly
ready to kill you.

Yes there is, e.g. in the 'singleton' pattern. Or when you have a global static class that holds objects that should be modifiable.

Usually though, you are right that you don't want to do this. But returning a const& is very common, for example in getter functions.

When you create an array class, if you overload the [] operator, then you need to return by reference and return by const reference. So in some situation, it is necessary.

references are more civilized than pointers only
because it looks easy to read, but it have all the
dangours that are associated with the pointers.

references are more civilized than pointers only
because it looks easy to read, but it have all the
dangours that are associated with the pointers.

Not quite. You can assign a null to a pointer but not to a reference.

Is there ANY EVER reason why i would return an object or variable by reference?

Yes, certainly. However, there's a strong distinction between returning by reference and returning by const reference. The latter gives you all of the potential performance benefits of returning by reference without the potential to lose control over your data.

Returning by non-const reference is still useful at times, but typically these times involve container classes and smart pointers. Yes, there are certainly dangers involved in aliasing, but it's our job as developers to decide when and where those dangers are justified.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.