views:

86

answers:

3

With pseudo code like this:

class FooBar {
public:
    int property;
    static int m_static;
}

FooBar instance1 = new FooBar();
FooBar instance2 = new FooBar();

If I set property of instance1, it would obviously not effect the second one. However, if I set the static property instead, the change should propagate to every instance of the class.

Will this also happen if instance1 and 2 are in different threads?

+2  A: 

Yes, there will only be one instance of the FooBar::static variable in the program. Of course, accessing the same variable from threads is inherently dangerous.

The instances don't matter at all, you can access the (public) static member from outside class instances, too.

Note: as written, this will not compile since you can't use "static" as the name of a variable, it's a reserved word.

unwind
+9  A: 
KennyTM
It's worth noting that some IDEs provide their own thread local storage, for example, Visual Studio provides __declspec(thread) or somesuch.
DeadMG
A: 

There is only one copy of static class variables and it is shared by all objects of the class and access to it must be synchronized because it is not thread - safe.

Ashish