local variables of static member functions

后端 未结 4 1268
终归单人心
终归单人心 2021-02-19 06:25

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: ar

相关标签:
4条回答
  • 2021-02-19 06:48

    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.)

    0 讨论(0)
  • 2021-02-19 06:49

    Unless explicitly declared as static, no they're not. They're on a stack, and each thread has a separate stack.

    0 讨论(0)
  • 2021-02-19 07:02

    No, a, b, and c are not static.

    Here's a sample that illustrates this:

    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;
    
    }
    
    0 讨论(0)
  • 2021-02-19 07:06

    The storage class of a, b, and c are (implicitly) auto which usually means on the call stack. They don't "inherit" static storage class from the method signature (which is a different meaning of static (yay for grossly overloaded keywords!)).

    0 讨论(0)
提交回复
热议问题