限定返回访问访问基础数据的返回电话

发布于 2025-02-04 07:59:28 字数 560 浏览 3 评论 0原文

我以前只使用指针工作,我不知道参考文献是否以返回状态的方式行事相同。 我可以链条多种返回的参考方法来访问数据,而不必担心包含垃圾的“悬挂”参考?还是参考将其传递给上面的功能通话之前,该引用会脱离范围?

如果这是传递参考的有效方法,请参见下面的代码(我们假设索引都在范围内)

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;
}

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;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

⒈起吃苦の倖褔 2025-02-11 07:59:28

是的,这是固定参考的有效方法。

您可以在功能中链接引用,而不必担心悬空引用(您应该担心指针)。只要存在m_container,就可以使用该引用,之后指向null

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文