Mikulas Dite
Mikulas Dite

Reputation: 7941

Static properties in C++

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?

Upvotes: 1

Views: 313

Answers (3)

Ashish
Ashish

Reputation: 8529

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.

Upvotes: 0

kennytm
kennytm

Reputation: 523514

A static member is essentially a global variable bound to a class (not an instance!). Global variables are not thread-local, hence change to that variable will be reflected in all threads.

(BTW, C++98 does not have the concept of threads. In C++0x you can make it thread-local (by §9.4.2/1) with

static thread_local int static_property;

but this is not widely supported.)

Upvotes: 9

unwind
unwind

Reputation: 399979

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.

Upvotes: 2

Related Questions