Why std :: thread accepts a functor by forwarding a link

Why std::threaddoes an object take a function parameter by forwarding a link, and then create a copy of the object with decay_copy? Would it be easier to just take a function object by value?

In general, why not create a template in order to take a function object by value? Can a reference link not be faked with reference_wrapper(which would be more explicit, as well as having a member operator()to call a stored function)?

+4
source share
1 answer

Why std::threaddoes an object accept a function parameter by forwarding a link and then create a copy of the object using decay_copy? Would it be easier to just take a function object by value?

It should have a copy of the function object in the repository, which it can guarantee, as long as the thread that it is about to start lasts.

The argument of the function to build std::threadwill not last so long, since the line in which it is created std::threadcan end long before the completion of the created stream.

Therefore, he must make a copy. If he took his argument by value, he would make a copy when the constructor was called, then he had to make another copy in the persistent storage. Taking it by forwarding the link, he makes exactly one copy.

, . , .

, , ?

move.

reference_wrappers ( , -() )?

, , -, .

, , .

+4

Source: https://habr.com/ru/post/1648893/


All Articles