Returning a reference

Started by
4 comments, last by paulecoyote 19 years, 6 months ago
Can anyone show me a simple example where returning a reference would produce the wrong result. I know the difference between int foo() {...} and int& foo() {...} but I can't think of when I should not return a reference. Thanks for the help!
Advertisement
Correct me if I'm wrong, because I don't do this kind of thing very often, but if you return a reference of a variable that is declared within that function (on the stack), the variable will be deallocated and the reference will be useless.
If you allocate something on the heap using new or malloc, that will work- the reference will still be good.
class cMyFoo{public:    const cVector3& GetPosition() const;    cVector3 GetParentPosition() const;private:    cVector3 m_Position;    cMyFoo *m_Parent;};const cVector3& cMyFoo::GetPosition() const{    return m_Position;}cVector3 cMyFoo::GetParentPosition() const{    if (m_Parent)    {        cVector3 pos;        pos = m_Position + m_Parent->GetPosition();        return pos;    }    return m_Position;}


no the first GetPosition() method will return reference to member varaiable of cMyFoo class. This allows us not to make a copy of that variable. In the second method we are adding pour position and parent position using local variable.

This is very simplified...
Ok I understand now. The important thing is not to return a local or temporary variable by reference because it may no longer be valid after the function goes out of scope, which means the caller of the function may get garbage.
You should also avoid returning references to private class members, doing so effectively allows what declaring the variable private is supposed to disallow - outside modification of variables in a way in which you have no control over.
Just to second Spudder - classes are there to encapsulate data and function together. Although possible and legal, if you start giving away references you would be breaking OO design rules - because you are taking away control of the internal data from being exlusively handled by its class methods.
Anything posted is personal opinion which does not in anyway reflect or represent my employer. Any code and opinion is expressed “as is” and used at your own risk – it does not constitute a legal relationship of any kind.

This topic is closed to new replies.

Advertisement