静态成员函数的局部变量 [英] local variables of static member functions

查看:183
本文介绍了静态成员函数的局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我们遇到了一个关于多线程环境中静态成员函数的问题。我们问自己,不能找到满意的答案的问题是:
是静态成员函数静态的局部varialbes吗?

Today we came accross a problem concerning static member functions in an multithreaded environment. The question we asked ourselves and couldn't find a satisfying answer is: are local varialbes of static member functions static as well?

// 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()并更改 a 通过分配rand()的新返回值,或者换句话说,两个线程都为a,b和c'操作一些内存位置。

Say you have two threads both calling A::test(). Is it possible that while thread 1 proccesses c = a + b thread 2 enters test() and changes the value of a by assigning the new return value of rand() or in other words do both threads operate an the some memory locations for a, b and c?

推荐答案

否。堆栈帧对于每个线程的函数调用是独立的,并且每个获得它自己的本地。 (如果您要访问实际的共享数据,则需要小心,例如类中的静态成员。)

No. The stack frames are independent for each thread's invocation of the function, and each gets its own locals. (You do need to be careful if you're accessing actual shared data e.g. static members in the class.)

这篇关于静态成员函数的局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆