When should I use std::bind?

前端 未结 2 747
广开言路
广开言路 2020-12-24 06:00

Every time I need to use std::bind, I end up using a lambda instead. So when should I use std::bind? I just finished removing it from one codebase,

2条回答
  •  执笔经年
    2020-12-24 06:03

    Here's something you can't do with a lambda:

    std::unique_ptr ptr = ...;
    return std::bind(&SomeType::Function, std::move(ptr), _1, _2);
    

    Lambdas can't capture move-only types; they can only capture values by copy or by lvalue reference. Though admittedly this is a temporary issue that's being actively resolved for C++14 ;)

    "Simpler and clearer" is a matter of opinion. For simple binding cases, bind can take a lot less typing. bind also is focused solely on function binding, so if you see std::bind, you know what you're looking at. Whereas if you use a lambda, you have to look at the lambda implementation to be certain of what it does.

    Lastly, C++ does not deprecate things just because some other feature can do what it does. auto_ptr was deprecated because it is inherently dangerous to use, and there is a non-dangerous alternative.

提交回复
热议问题