Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

stl

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 have to use reference wrappers.

  1. Does anyone know why this makes a good default behaviour? Esp. in C++11 with rvalue reference and perfect forwarding, it seems to me that it makes more sense to just perfectly forward the arguments.

  2. std::make_shared though doesn't always copy/move but just perfectly forward the provided arguments. Why are there two seemingly different behaviour of forwarding arguments here? (std::thread and std::bind that always copy/move vs std::make_shared that don't)

like image 377
ryaner Avatar asked May 08 '12 17:05

ryaner


1 Answers

make_shared forwards to a constructor that is being called now. If the constructor uses call by reference semantics, it will get the reference; if it does call by value, it will make a copy. No problem here either way.

bind creates a delayed call to a function that is called at some unknown points in the future, when the local context is potentially gone. If bind were using perfect forwarding, you would have to copy the arguments that are normally sent byreference and not known to be live at the time of the actual call, store them somewhere, and manage that storage. With the current semantics bind does it for you.

like image 130
n. 1.8e9-where's-my-share m. Avatar answered Oct 02 '22 23:10

n. 1.8e9-where's-my-share m.