C++11 - Caution on using lambda inside lambda.

less than 1 minute read

When you create a lambda and if the lambda create another lambda in asynchronous way by using thread, you need to be very careful on capturing values. If you capture all variables(including local variables) by references, you will likely make a mistake by using accidentally local variables inside another lambda. If you are lucky application will crash, if not application will corrupt heap in randomly.

You can find similar information from the link(http://stackoverflow.com/questions/6216232/c-nested-lambda-bug-in-vs2010-with-lambda-parameter-capture).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void Func()
{
   FireCall(pEvent, idx + 1, [data](_IEvent* pCall)->HRESULT
   {
      return pCall->OnEvent(data);
   });
}
bool FireCall(_IEvent* pEvent, DWORD idx, boost::function<HRESULT(_IEvent*)> func)
{
   IStream* pStream = NULL;
   HRESULT hRes = CoMarshalInterThreadInterfaceInStream(IID__Event, pEvent, &pStream);
   pEvent->Release();
   // create another lambda, it should pass variable by value.
   m_threadPool.Schedule([idx, pStream]()
   {
       _IEvent* pCallEvent = NULL;
       auto res = CoGetInterfaceAndReleaseStream(pStream, IID, (void**)&pCallEvent);
       if (SUCCEEDED(res))
          func(pCallEvent);
   });
}