Home > Back-end >  Chaining return-by-reference calls to access underlying data
Chaining return-by-reference calls to access underlying data

Time:06-05

I worked previously only with pointers and i don't know if references behave the same way in return-statements. Can I chain multiple return-by-reference methods to access data without fearing for a "dangling" reference which contains garbage? Or would the reference go out of scope before passing it to the function-call above?

See the code below if this is a valid way to pass references (we assume that the indexes are all in range)

struct Data {
    //Non-Trivial Data
}

class Container {
    public:
        Data& get(int index) { return m_Collection[index]; }
    private:
        Data[100] m_Collection;
}


class ContainerCollection {
    public:
        Data& get(int containerindex, int dataindex) { return m_Container[containerindex].get(dataindex); }
    private:
        Container[3] m_Container;
}

CodePudding user response:

Yes, this is a valid way of chaining references.

You can chain references within functions without worrying about dangling references (which you should worry with pointers). As long as m_Container exists, the reference is available, after that it points to NULL.

  • Related