Greeneco
Greeneco

Reputation: 741

C++ - Return reference to a vector element

I want to return a reference to a single element in a vector I get as param and then compare there memory addresses. A simplified example of my code is shown below:

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

Using this I get the following error message:

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

How can I return reference to a single vector element?

Upvotes: 0

Views: 2396

Answers (1)

Guido Niewerth
Guido Niewerth

Reputation: 156

You're passing the vector by value so you're returning a reference to a temporary element. If you pass the vector by reference you should be fine.

Upvotes: 7

Related Questions