Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is std::bind still useful compared to lambdas? [duplicate]

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?

like image 214
deft_code Avatar asked Nov 11 '11 01:11

deft_code


People also ask

Why prefer lambda over bind?

A key advantage of lambdas is they can reference member functions statically, while bind can only reference them through a pointer.

What is std:: bind used for?

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.

Is std :: function heavy?

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).

Is a lambda a std:: function?

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.


2 Answers

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.

like image 127
Luc Danton Avatar answered Sep 20 '22 22:09

Luc Danton


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.)

like image 32
Kerrek SB Avatar answered Sep 18 '22 22:09

Kerrek SB