【问题标题】:C++ - Return reference to a vector elementC++ - 返回对向量元素的引用
【发布时间】:2018-05-27 17:57:53
【问题描述】:

我想返回对作为参数获得的向量中单个元素的引用,然后比较那里的内存地址。我的代码的简化示例如下所示:

const int &test(std::vector<int> i) {
    return i.at(3);
}

TEST(test, all_test) {
    const std::vector<int> i = {1,2,3,4,5};
    const int &j = test(i);
    ASSERT_THAT(&j, Eq(&i.at(3)));
}

使用这个我收到以下错误消息:

Failure
Value of: &j
Expected: is equal to 0x55da7899d4dc
  Actual: 0x55da7899d4fc (of type int const*)

如何返回对单个矢量元素的引用?

【问题讨论】:

    标签: c++ reference return stdvector


    【解决方案1】:

    您正在按值传递向量,因此您正在返回对临时元素的引用。如果你通过引用传递向量,你应该没问题。

    【讨论】:

    • 使用const int &amp;test(std::vector&lt;int&gt; &amp;i) 最终也会导致不同的地址。你能举个例子吗?
    • 通过引用传递并将第一个参数标记为const(否则无法编译,您也可以将i设为非const)使您的代码按预期工作。跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多