What is the rationale behind std::bind and std::thread always copying arguments?

前端 未结 5 1414
你的背包
你的背包 2021-02-20 03:35

It\'s pretty well known that the default behaviour of std::bind and std::thread is that it will copy (or move) the arguments passed to it, and to use reference semantics we will

5条回答
  •  情歌与酒
    2021-02-20 04:09

    For both std::bind and std::thread, the invocation of the function on the given arguments is deferred from the call site. In both cases, exactly when the function will be called is simply unknown.

    To forward the parameters directly in such a case would require storing references. Which may mean storing references to stack objects. Which may not exist when the call is actually executed.

    Oops.

    Lambdas can do it because you're given the ability to decide, on a per-capture basis, whether you want to capture by reference or value. Using std::ref, you can bind a parameter by reference.

提交回复
热议问题