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

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

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

   // 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))
This entry was posted in C++, Programming. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s