C++返回对非复制对象向量的引用

发布于 01-17 11:35 字数 363 浏览 3 评论 0原文

我有class a ,带有禁用的复制语义和类b,其中包含a's的向量。如何编写B的成员函数,该功能返回引用a的向量。

对于那些知道这里生锈的人是我要做的事情(用锈语表达):

struct A {/* ... */}

struct B {
    data: Vec<A>,
}

impl B {
    pub fn data(&self) -> &Vec<A> {
        &self.data
    }
}

I have class A with disabled copy semantics and class B which contains vector of A's. How can I write a member function of B that returns reference to the vector of A's?.

For those knowing Rust here is what I am trying to do (expressed in the Rust language):

struct A {/* ... */}

struct B {
    data: Vec<A>,
}

impl B {
    pub fn data(&self) -> &Vec<A> {
        &self.data
    }
}

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

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

发布评论

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

评论(1

疯狂的代价2025-01-24 11:35:52

正如@molbdnilo所说的那样,我的错误是我使用了auto data = b.data();而不是auto&amp; data = b.data();。因此,以下示例正在工作,并显示如何做我问的事情:

#include<vector>
class A
{
public:
    A(const A&) = delete;
    A(A&&) = default;
    A& operator=(const A&) = delete;
    A& operator=(A&&) = default;
private:
    /* some data */
};

class B
{
public:
    B(): m_data {} {}
    const std::vector<A>& data() const {
        return this->m_data;
    }
private:
    std::vector<A> m_data;
};

int main()
{
    auto b = B();
    auto& data = b.data();
}

As @molbdnilo stated my error was that I used auto data = b.data(); instead of auto& data = b.data();. Therefore following example is working and shows how to do what I asked:

#include<vector>
class A
{
public:
    A(const A&) = delete;
    A(A&&) = default;
    A& operator=(const A&) = delete;
    A& operator=(A&&) = default;
private:
    /* some data */
};

class B
{
public:
    B(): m_data {} {}
    const std::vector<A>& data() const {
        return this->m_data;
    }
private:
    std::vector<A> m_data;
};

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