4

I have following code

#include <iostream>
#include <vector>
#include <functional>

int main() {
    std::vector<double> v(5, 10.3);
    std::vector<double>& r = v;
    //std::vector<std::reference_wrapper<double>> r(v.begin(),v.end());
    for (auto& i : v)
        i *= 3;
    for (auto i : r)
       std::cout << i << " ";
    std::cout << std::endl;
}

I am using reference of the vector 'r' using '&' operator and in the second line which I commented out I am using std::reference_wrapper of C++. Both do pretty much the same job? But I think there must be a purpose of making std::reference_wrapper even if we had '&' to do the job. can anyone explain please?

2
  • Do r.resize(200) and you'll see the difference - one refers to the vector, others refers to the doubles. Commented Jul 7, 2015 at 14:07
  • & here is not an operator. Commented Jul 7, 2015 at 15:08

1 Answer 1

10

First, the two lines

std::vector<double>& r = v;
std::vector<std::reference_wrapper<double>> r(v.begin(),v.end());

Don't mean the same thing. One is a reference to a vector of doubles, the other one is a vector of "references" to doubles.

Second, std::reference_wrapper is useful in generic programming (ie: templates) where either a function might take its arguments by copy, but you still want to pass in an argument by reference. Or, if you want a container to have references, but can't use references because they aren't copyable or movable, then std::reference_wrapper can do the job.

Essentially, std::reference_wrapper acts like a "&" reference, except that it's copyable and reassignable

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

1 Comment

Perfect example of the functions taking arguments by copy section is std::async and std::thread

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.