c++ lambdas和静态变量的预期行为
Expected behaviour with c++ lambdas and static variables
我正在使用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将是独立的类,尽管它们具有相同的定义。
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 将数组的地址分配给变量并删除
- 为"adjacent"变量赋值时出现问题
- enum是C++中的宏变量还是整数变量
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 用C++中的一个变量定义一个常量
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 你能重载对象变量名本身返回的内容吗
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 尝试通过多个向量访问变量时,向量下标超出范围
- 试图让变量检查数组中的某些内容
- Cpp-Tuple使用带有变量的get
- 将包含C样式数组的对象初始化为成员变量(C++)
- 当vector是tje全局变量时,c++中vector的内存管理
- Lambdas和引用捕获局部变量:在范围之后访问
- c++ lambdas和静态变量的预期行为
- 如何在std::fill()中使用c++的lambdas局部变量
- c++11 lambdas是否捕获它们不捕获的变量't使用