C++ 静态成员函数的局部变量
今天我们遇到了一个关于多线程环境中静态成员函数的问题。我们自问了一个问题,但没有找到令人满意的答案: 静态成员函数的局部变量也是静态的吗C++ 静态成员函数的局部变量,c++,C++,今天我们遇到了一个关于多线程环境中静态成员函数的问题。我们自问了一个问题,但没有找到令人满意的答案: 静态成员函数的局部变量也是静态的吗 // header class A { static int test(); } // implementation int A::test() { int a = rand(); int b = rand(); int c = a + b; return c; } 假设有两个线程都在调用A::test()。当线程1处理c=a+b时
// header
class A
{
static int test();
}
// implementation
int A::test()
{
int a = rand();
int b = rand();
int c = a + b;
return c;
}
假设有两个线程都在调用A::test()。当线程1处理
c=a+b
时,线程2是否可能进入test(),并通过分配rand()的新返回值来更改a
的值,或者换句话说,两个线程是否都操作a的某些内存位置,b和c?否。堆栈帧对于每个线程调用函数是独立的,并且每个都有自己的局部变量。(如果访问实际共享数据,例如类中的静态成员,则需要小心。)a、b和c的存储类(隐式)是自动的,这通常意味着在调用堆栈上。它们不会从方法签名中“继承”静态存储类(这是静态的另一种含义(是的,用于严重重载的关键字!)。除非明确声明为静态,否则它们不是。它们位于堆栈上,每个线程都有一个单独的堆栈。否,a、b和c不是静态的
下面的示例说明了这一点:
class Val
{
public:
Val() { cout << "Val" << this << endl; }
~Val() { cout << "~Val" << this << endl; }
int n_;
};
class A
{
public:
static int test()
{
Val a;
a.n_ = rand();
Val b;
b.n_ = rand();
Val c;
c.n_ = a.n_ + b.n_;
return c.n_;
}
};
int main()
{
srand(time(0));
for( int i = 0; i < 5; ++i )
{
cout << "Test = " << A::test() << endl;
}
return 0;
}
class-Val
{
公众:
Val(){我之所以能在这里登陆,是因为我对一个类似的bug有着类似的怀疑。在我的例子中,while(true)
循环没有中断
,因为函数是[[noreturn]]
。经验教训。希望这能对其他人有所帮助。