Skip to content
Search

C++:Lambda

lastmod 2018-08-17created 2014-11-1116 edits

Syntax

Lambda-syntax.png

Explanation

mutable
allows body to modify the parameters captured by copy, and to call their non-const member functions.

How to use

Lambdas are used as follows.

  • []{}
  • [](인자){}
  • [](인자)->반환값{}
  • [](인자)->반환값{}
  • [](인자)mutable ->반환값{}
  • [](인자)mutable throw() ->반환값{}
  • [](인자)mutable ->반환값{}(): direct call.

Each part is named as follows.

  • []: Lambda Introducer
  • (): Parameter Specifier
  • {}: Lambda Body

List of caputre

  • []: captures nothing
  • [&x]: capture by reference, x only
  • [x]: capture by value, x only
  • [&]: capture by reference, all outer variables
  • [=]: capture by value, all outer variables
  • [x,y]: capture x, y by value
  • [&x,y]: x is captured by reference, y is captured by value
  • [&x, &y]: capture x, y by reference
  • [&, y]: capture by reference all values except y
  • [=, x]: capture by value all values except x

Tip

std::function<T> to c-style function pointer

In short, it is impossible.

The result of std::bind is a complicated C++ object. It has to store all the bound arguments,
for example. So it is most definitely not convertible to a pointer to function.

The callback specification you're dealing with apparently doesn't allow a "user data" payload,
so there's nowhere to hide a pointer to a C++ object which you could use to invoke a non-static member funtion.
This means you will have to call a global or static member function,
or resort to a global/static member/per-thread variable to store the object pointer.

Troubleshooting

Function parameter

When a function object is passed as a function argument and called inside a lambda, as below, it may not be called correctly.

using accept_handle = std::function<void(error_code const &, Session *)>;
// ...
void accept(accept_handle handler, Session * new_session) {
    _acceptor.async_accept(new_session->getSocket(), [&](error_code const & error) {
        handler(error, new_session);
    });
}

In this case, do not use the lambda's All Reference Capture ([&]). If you do, the accept_handle handler argument disappears along with the stack unwinding when the function ends. In such cases, pass the variables directly, as below.

using accept_handle = std::function<void(error_code const &, Session *)>;
// ...
void accept(accept_handle handler, Session * new_session) {
    _acceptor.async_accept(new_session->getSocket(), [handler, new_session](error_code const & error) {
        handler(error, new_session);
    });
}

Favorite site

References


  1. Programming_IT_-_C++_Lambda_function.pdf ↩

  2. Vallista's_Development_Lap-C++11-Lambda_Expression_and_Functor.pdf ↩

  3. Amateur_Game_Programmer_FromPt-Lambda.pdf ↩

  4. ProjectK-C++0x-Lambda.pdf ↩