开发者

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()开发者_Go百科;

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?


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜