伪代码如下:
class FooBar {
public:
int property;
static int m_static;
}
FooBar instance1 = new FooBar();
FooBar instance2 = new FooBar();
如果我设置实例 1 的属性,显然不会影响第二个实例。但是,如果我改为设置静态属性,则更改应传播到该类的每个实例。
如果 instance1 和 2 在不同的线程中,是否也会发生这种情况?
最佳答案
static
成员本质上是绑定(bind)到类(不是实例!)的全局变量。全局变量不是线程局部变量,因此对该变量的更改将反射(reflect)在所有线程中。
(顺便说一句,C++98 没有线程的概念。在 C++0x 中,您可以使用 使其成为线程局部的(根据 §9.4.2/1)
static thread_local int static_property;
但这是 not widely supported .)
关于c++ - C++ 中的静态属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3584246/