C++ Weekly - Ep 16 Avoiding `std::bind`

C++ Weekly With Jason Turner · 26K views · 2016 · 13:53

Open on YouTube

C, C++, Rust, Go & systems languagestutorial

Why Stack Overflow recommends it

Stack Overflow users link it when someone uses `std::bind` or `boost::bind` and they want to justify switching to lambdas for clarity and better generated code.

Recommended by 2 people across 2 different months, 2016 to 2022.

What it is

A short episode of Jason Turner's C++ Weekly series arguing that you should replace `std::bind` with lambdas. He compares the readability and the compiler output of the two approaches, following up on the previous episode that showed how `std::bind` works.

What people said

Recommends Qaz · 2017-11 · Stack Overflow · on “Getting undeclared args when trying to bind std::function using parameter pack”

@Pins, `std::bind` also works for member functions. In fact, it's one of the examples on cppreference [LINK] . Regardless, hooking up variadics to either is painful at best unless `std::bind_front` [LINK] makes it through. There's a C++ Weekly [this video] video on avoiding `bind` with lambdas, but it sounds like some extra variadic template material might be beneficial.

Recommends Marcin Poloczek · 2021-08 · Stack Overflow · on “Understanding C++ stack object allocation”

Use lambdas instead of std::bind, it's slower and generates a lot of boilerplate assembly on some compilers (especially older ones). Check out Jason Turner's video to learn more: [this video]

Cites Jonathan Mee · 2016-07 · Stack Overflow · on “how bind function works for functional objects in c++”

@PaulVarghese I love `bind` for it's clarity and for the familiarity I have with it from back in the days of `bind_1st` and `bind_2nd`. But honestly, compilers have deffered optimization of `bind` for optimization of lambdas. This is at least true of gcc: [this video] I'm not certain where Visual Studio lands on everything, but I think the general climate says prefer lambdas to `bind`s.

Cites Domenico · 2022-09 · Stack Overflow · on “move boost::bind to lambda”

I am doing some tutorial for boost::asio that is not very recent I think so I decide to make some adjustment. In particular I remove all the boost::bind occurrence to lambdas as explained in [this video] for example: // Class Connection definition and its members declaration class Connection : public std::enable_shared_from_this<Connection> { friend class Acceptor; private: void StartSend(); void StartRecv(std::int32_t total_bytes); ... } ... // Connection::StartRecv definition void Connection::StartRecv(int32_t total_bytes) { /* m_socket.async_read_some( _asio::buffer(m_recv_buffer), m_io_strand.wrap( boost::bind(&Connection::HandleRecv, shared_from_this(), boost::placeholders::_1, boost::placeh