Expected behaviour with c++ lambdas and static variables

c++, c++11, lambda, static, visual-studio-2013

Solution

A lambda is not an object that is created when needed, but a shorthand for an inline definition of a class. Your invocation above would be roughly equivalent to:

class SomeLambda {
 public:
  const char* operator() (const int& i) {
    static char buf[33];
    sprintf(buf, "%d", i);
    return buf;
  }
};

...
pHasLambda->Init(SomeLambda());

The static initialization rules there have the same meaning as any function level static for a member function.

If you instead had two different lines creating the lambda ex:

auto x = []() { static char buf[99]; use_buf(buf); return buf; };
auto y = []() { static char buf[99]; use_buf(buf); return buf; };

Then x and y would be separate classes despite having identical definitions.

Problem

I'm using VS2013, and discovered what appears to me to be strange behaviour when using multiple instances of a class that contains lambdas, and those lambdas contain static variables. The static variables appear to be shared. Example code, very much trimmed down but still captures the essence: ``` class HasLambda { public: typedef const char* ( *ToCharPtr ) ( const int& ); void Init( ToCharPtr pfnToCharPtr ) { m_pfnCharPtrConverter = pfnToCharPtr; } const char* IntToString( int i ) { return m_pfnCharPtrConverter( i ); } static HasLambda* Make() { HasLambda* pHasLambda = new HasLambda; pHasLambda->Init( [] ( const int &i ) -> const char* { static char buf[ 33 ]; sprintf( buf, "%d", i ); return buf; } ); return pHasLambda; } protected: ToCharPtr m_pfnCharPtrConverter; }; int _tmain(int argc, _TCHAR* argv[]) { HasLambda* a; a = HasLambda::Make(); HasLambda* b; b = HasLambda::Make(); const char* aValue = a->IntToString( 7 ); printf( "a: %s\n", aValue ); const char* bValue = b->IntToString( 42 ); printf( "b: %s\n", bValue ); printf( "a: %s\n", aValue ); return 0; } ``` The output I get is: ``` a: 7 b: 42 a: 42 ``` I would have expected the second a: value to be the same as the first. Am I seeing a compiler bug, or am I misunderstanding the way lambdas and static variables therein work? Am I using the lambda wrong in some way?

Original source