mercredi 26 octobre 2016

Expected behaviour with c++ lambdas and static variables

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?

Aucun commentaire:

Enregistrer un commentaire