Possible Duplicate:
Bind Vs Lambda?
My use of std::bind
had dropped to 0 now that lambdas have gained wide support.
Are there any problems that std::bind
is uniquely suited for over a lambda function?
Was there a compelling reason to keep std::bind
in the standard once lambdas where added?
A key advantage of lambdas is they can reference member functions statically, while bind can only reference them through a pointer.
std::bind. Returns a function object based on fn , but with its arguments bound to args . Each argument may either be bound to a value or be a placeholder: - If bound to a value, calling the returned function object will always use that value as argument.
Note that when talking about overhead of std::function (i.e. that std::function is "heavy"), usually the performance overhead is meant. Its memory overhead will be minor (around 2 extra pointers, I'd guess).
Lambda's type One important thing to note is that a lambda is not a std::function . It is true that a lambda can be assigned to a std::function , but that is not its native type.
You can capture by value or by reference, and the problem is that capture by value really means 'capture by copy'. This is a show stopper for a move-only type. So you can't use a lambda to do the following:
struct foo { void bar() {} };
std::unique_ptr<foo> f { new foo };
auto bound = std::bind(&foo::bar, std::move(f));
static_assert( std::is_move_constructible<decltype(bound)>::value, "" );
bound();
IIRC the Standard Committee briefly considered allowing arbitrary expression inside a lambda capture list to solve this (which could look like [std::move(f)] { return f.bar(); }
), but I don't think there was a solid proposal and C++11 was already running late.
That and the restriction to monomorphic behaviour with lambdas are the deal breakers for me.
bind
is great for creating references to bound member function:
Foo x;
auto f = std::bind(&Foo::bar, &x, 12, true);
register_callback(f);
Edit: As Luc Danton demonstrates, this construction is very flexible and allows for the instance pointer to come in a surprising variety of guises (e.g. smart pointers).[/]
If feasible, a lambda is probably preferable, especially since it offers greater potential for optimization, but bind-expressions still have their place.
(In any event, auto
is preferable over std::function
for the type to store the callable object.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With