Why did C++11 introduce std::ref?

C++ itself has references (&), why did C++11 introduce std::ref?

  The main consideration is that when functional programming (such as std::bind) is used, the parameters are directly copied, not referenced. The following example:

copy code
#include <functional>
#include <iostream>
 
void f(int& n1, int& n2, const int& n3)
{
    std::cout << "In function: " << n1 << ' ' << n2 << ' ' << n3 << '\n';
    ++n1; // increments the copy of n1 stored in the function object
    ++n2; // increments the main()'s n2
    // ++n3; // compile error
}
 
intmain()
{
    int n1 = 1, n2 = 2, n3 = 3;
    std::function<void()> bound_f = std::bind(f, n1, std::ref(n2), std::cref(n3));
    n1 = 10;
    n2 = 11;
    n3 = 12;
    std::cout << "Before function: " << n1 << ' ' << n2 << ' ' << n3 << '\n';
    bound_f();
    std::cout << "After function: " << n1 << ' ' << n2 << ' ' << n3 << '\n';
}
copy code
Output:
Before function: 10 11 12
In function: 1 11 12
After function: 10 12 12

  After the above code executes std::bind, the value of n1 in function f() is still 1, and n2 and n3 are changed to modified values. Indicates that std::bind uses a copy of the parameter rather than a reference. Specifically why std::bind does not use references, there may be some requirements that make the designers of C++11 think that copy should be used by default. If users have requirements, add std::ref.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324602655&siteId=291194637