0

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?

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Using const int &test(std::vector<int> &i) also results in a different address in the end. Could you give an working example?
Passing by reference and marking the first parameter as const (otherwise it doesn't compile, you can just make i non-const either) makes your code work as you intended.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.