When is the use of std::ref necessary?

后端 未结 3 1043
[愿得一人]
[愿得一人] 2020-12-14 07:37

Consider:

std::tuple func (const A& a) 
{
  return std::make_tuple( 0 , std::ref(a) );
}

Is the std::re

相关标签:
3条回答
  • 2020-12-14 08:04

    std::ref does not make a reference, so in your code sample it doesn't do what you expect. std::ref creates an object that behaves similarly to a reference. It may be useful, for example, when you want to instantiate a functor, and pass a reference-like version of it to a standard library algorithm. Since algorithms take functors by value, you can use std::ref to wrap the functor.

    0 讨论(0)
  • 2020-12-14 08:07

    One of the example where std::ref is necessary:

    void update(int &data)  //expects a reference to int
    {
        data = 15;
    }
    int main()
    {
        int data = 10;
    
        // This doesn't compile as the data value is copied when its reference is expected.
        //std::thread t1(update, data);         
    
        std::thread t1(update, std::ref(data));  // works
    
        t1.join();
        return 0;
    }
    

    The std::thread constructor copies the supplied values, without converting to the expected argument type (which is reference type in this case, seeupdate()). So we need to wrap the arguments that really needs to be references in std::ref.

    0 讨论(0)
  • 2020-12-14 08:18
    • make_tuple(0, a) makes a tuple<int, A>.
    • make_tuple(0, ref(a)) makes a tuple<int, reference_wrapper<A>>.
    • You can also say tuple<int, A&> t(0, a); for a tuple you can't make with make_tuple, or use std::tie.
    0 讨论(0)
提交回复
热议问题