What would be a “Hello, World!” example for “std::ref”?

后端 未结 4 2043
星月不相逢
星月不相逢 2021-01-30 01:54

Can somebody give a simple example which demonstrates the functionality of std::ref? I mean an example in which some other constructs (like tuples, or data type tem

4条回答
  •  野的像风
    2021-01-30 02:44

    You should think of using std::ref when a function:

    • takes a template parameter by value
    • or copies/moves a forwarding reference parameter, such as std::bind or the constructor for std::thread.

    std::ref is a value type that behaves like a reference.

    This example makes demonstrable use of std::ref.

    #include 
    #include 
    
    void increment( int &x )
    {
      ++x;
    }
    
    int main()
    {
      int i = 0;
    
      // Here, we bind increment to (a copy of) i...
      std::bind( increment, i ) ();
      //                        ^^ (...and invoke the resulting function object)
    
      // i is still 0, because the copy was incremented.
      std::cout << i << std::endl;
    
      // Now, we bind increment to std::ref(i)
      std::bind( increment, std::ref(i) ) ();
    
      // i has now been incremented.
      std::cout << i << std::endl;
    }
    

    Output:

    0
    1
    

提交回复
热议问题