Modern (Effective) C++ - Using init captures

Sometimes the capture-by-value nor capture by reference is not sufficient. In some cases we would like the to move the variables. This happens when copying the object into closure might be prohibitively expensive, and capturing the object by reference might lead to dangling reference. And there are some types which can only be moved and not copied ( for example, std::unique_ptr).

C++11 does not have move only capture. But the lack of it was recognized and a powerful mechanism called init capture, which does a lot more than just move-capture. The below program demonstrates the concept -



The capture can be seen on line no 8. upLmb i.e the variable of the LHS of assignment refers to the data member of closure.The RHS refers to the local variable which is captured.

The above program works in C++14 onwards, because init capture was introduced in C++14. To emulate this behaviour in C++11, we can std::bind to create bind objects.


Modern (Effective) C++ - Using init captures Modern (Effective) C++  - Using init captures Reviewed by zeroingTheDot on March 29, 2018 Rating: 5

No comments:

Powered by Blogger.