In the example with threads, I met a parameter passing through the ref function from the standard library, it is not clear how to use it, why can't the variable be passed just by its name?

Here is the actual example:

#include <iostream> #include <thread> void threadFunction(int &a) { a++; } int main() { int a = 1; std::thread thr(threadFunction, std::ref(a)); // что делает функция ref()? почему нельзя передовать просто переменную по ее имени? thr.join(); std::cout << a << std::endl; return 0; } 

added later

when passing simply by the name std :: thread thr (threadFunction, a); the program does not compile and crashes

error console

    2 answers 2

    By name - the value will remain. And you just need a synonym for the same area of ​​memory. As a result, when the threadFunction , you will print 2. If you remove std::ref , then 1.

    And here is a more detailed explanation:

    The third problem is solved using the template functions std::ref and std::cref declared in the header <functional> . The first returns a link to the object, the second returns a constant link. These functions are often needed when working, for example, with std::bind . There is one reason - to pass a link to the binder, and not a copy of the object. If you are working with threads ( std::thread ) and you need to pass arguments by reference when initializing the thread object, you will also need the functions std::ref and std::cref .

    • one
      when passing simply by the name std :: thread thr (threadFunction, a); the program does not compile and falls with an error - perfect
    • Well, then yes - the thread constructor expects Args&& , and the type a - int& , ref creates a temporary reference_wrapper object that satisfies the rvalue requirement. - Monah Tuk
    • @perfect change void threadFunction (int & a) to void threadFunction (int a) and everything will compile - Embedder

    Such methods capture data only by value. In order to prokinut the link and made this wrapper. The result is that the wrapper itself is then copied, but it continues to hold the link inside.