12

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)

3
  • If you bind a reference to a local, you'll be in trouble.
    – mfontanini
    May 8, 2012 at 17:18
  • 2
    I won't be if the called function doesn't exist beyond the scope of the local. There are a lot of things in C++ that lets you blow your foot off. My question is more to the point that this behaviour seems to be less intuitive.
    – ryaner
    May 8, 2012 at 17:40
  • At some point my answer contained a "and that local goes out of scope", but apparently it got erased after editting :S
    – mfontanini
    May 8, 2012 at 17:57

5 Answers 5

16

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.

7

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.

1
  • Makes sense. Voted up! Would accept if I were allowed to accept two answers. Thanks.
    – ryaner
    May 8, 2012 at 18:13
2

The most probable reason is simply that C++ uses value semantics by default pretty much everywhere. And using references could easily create issues concerning the lifetime of the referred to object.

3
  • But isn't it C++'s principle that the programmer knows what it wants best? In the case of dangling reference, the programmer should be careful that its function's parameters will be by value if it wants to, and when our function's parameter takes a reference, I'd expect things to be forwarded perfectly as reference for whatever risk. Just a thought.
    – ryaner
    May 8, 2012 at 17:32
  • 1
    No. The principle is that the programmer does not pay in performance for features he does not use. The "know what are you doing" thing is only means to achieve this end, not the end in and by itself. May 8, 2012 at 17:59
  • 1
    C++ has a lot of principles:-). One of the most fundamental ones is that it uses value semantics by default; you have to explicitly request a reference or a pointer for it to do otherwise. (Of course, the standard library doesn't always follow this rule---iterators and predicates are always by value, but other things tend to vary.) May 8, 2012 at 17:59
1

std::bind creates a callable which is detached from the call site of std::bind, thus it makes much sense to capture all arguments by value by default.

The general use case is to be identical to passing a function pointer to a function without knowing where it might end up.

Lambdas give more flexibility for the programmer to decide whether the lambda will live beyond the scope arguments are captured from.

1
  • Is it the same case for std::thread? In the case of thread start function it's less likely that it will be written as lambda. And forcing to use lambda's closure to pass by reference there can seem weird? Lambdas doesn't seem to solve all problems caused by this here.. I think?
    – ryaner
    May 8, 2012 at 17:34
1

I did in fact write a small utility that creates a delayed invocation functor (somewhat std::bind-like, but without the nested bind expressions/placeholders features). My main motivation was this case that I found counter-intuitive:

using pointer_type = std::unique_ptr<int>;
pointer_type source();
void sink(pointer_type p);

pointer_type p = source();

// Either not valid now or later when calling bound()
// auto bound = std::bind(sink, std::move(p));
auto bound = std::bind(
    [](pointer_type& p) { sink(std::move(p)); }
    , std::move(p) );
bound();

The reason for that adaptor (which moves its lvalue ref argument to sink) is that the call wrapper return by std::bind always forwards the bound arguments as lvalues. This wasn't a problem with e.g. boost::bind in C++03 since that lvalue would either bind to a reference argument of the underlying Callable object or to a value argument via a copy. Doesn't work here since pointer_type is move-only.

The insight that I got is that there really are two things to consider: how the bound arguments should be stored, and how they should be restored (i.e. passed to the Callable object). The control that std::bind grants you is as follows: arguments are either stored in a shallow (via the use of std::ref) or regular manner (using std::decay with perfect forward); they are always restored as lvalues (with cv-qualifiers inherited from the owning call wrapper). Except that you can bypass the latter with a small on-site adaptor lambda expression like I just did.

It's arguably a lot of control and a lot of expression for relatively little to learn. In comparison my utility has semantics like bind(f, p) (decay and store copy, restore as lvalue), bind(f, ref(p)) (store shallowly, restore as lvalue), bind(f, std::move(p)) (decay and store from move, restore as rvalue), bind(f, emplace(p)) (decay and store from move, restore as lvalue). This feels like learning an EDSL.

3
  • It is a very interesting idea, could you point us to the implementation so we can explore it? Also, the resulting functor can logically be called only once? And what happened if we copy the resulting functor?
    – authchir
    May 10, 2012 at 3:19
  • @authchir Code here (and things like emplace are from here). You're correct that it's only correct to call the functor once (further calls forward an empty pointer_type), and in addition to that the call wrapper is move-only. This all also applies to the equivalent std::bind usage.
    – Luc Danton
    May 10, 2012 at 3:28
  • Also unit test shows typical usage.
    – Luc Danton
    May 10, 2012 at 3:34

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.