c++ lambdas和静态变量的预期行为

Expected behaviour with c++ lambdas and static variables

本文关键字:变量 lambdas 静态 c++      更新时间:2023-10-16

我正在使用VS2013,并发现在使用包含lambdas的类的多个实例时,我似乎是奇怪的行为,而这些lambdas包含静态变量。静态变量似乎是共享的。

示例代码,非常精简,但仍然抓住了本质:

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: %sn", aValue );
    const char* bValue = b->IntToString( 42 );
    printf( "b: %sn", bValue );
    printf( "a: %sn", aValue );
    return 0;
}
我得到的输出是:
a: 7
b: 42
a: 42

我希望第二个a:值与第一个相同。我看到一个编译器错误,或者我误解了方式lambdas和静态变量在其中的工作?我用错了吗?

lambda不是在需要时创建的对象,而是类的内联定义的简写。上面的调用大致相当于:

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

这里的静态初始化规则与成员函数的任何函数级静态规则具有相同的含义。

如果你有两个不同的行来创建lambda ex:

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

那么x和y将是独立的类,尽管它们具有相同的定义。