嵌套 class 中的静态成员是否具有封闭 class 的静态持续时间?
Does a static member inside a nested class have static duration for the enclosing class?
如果我有嵌套的 classes,并且这些嵌套的 classes 有静态成员,那些成员对于封闭的 class 仍然是静态的吗?例如,如果我有
class Enclosing {
public:
Enclosing();
private:
class Nested {
public:
Nested();
private:
static int thing;
};
};
如果我这样做
auto A = Enclosing();
auto B = Enclosing();
A
和 B
可以为 thing
设置不同的值吗?
Will A
and B
be able to have different values for thing
?
不,它们不会有不同的值。所有实例都将看到 thing
的相同值; class 的嵌套在这里没有影响。
static
成员变量是 "associated with the class"(即与 class 的实例关联的非静态成员)。 From cppreference;
Static data members are not associated with any object. They exist even if no objects of the class have been defined. If the static member is declared thread_local
(since C++11), there is one such object per thread. Otherwise, there is only one instance of the static data member in the entire program, with static storage duration.
如果我有嵌套的 classes,并且这些嵌套的 classes 有静态成员,那些成员对于封闭的 class 仍然是静态的吗?例如,如果我有
class Enclosing {
public:
Enclosing();
private:
class Nested {
public:
Nested();
private:
static int thing;
};
};
如果我这样做
auto A = Enclosing();
auto B = Enclosing();
A
和 B
可以为 thing
设置不同的值吗?
Will
A
andB
be able to have different values forthing
?
不,它们不会有不同的值。所有实例都将看到 thing
的相同值; class 的嵌套在这里没有影响。
static
成员变量是 "associated with the class"(即与 class 的实例关联的非静态成员)。 From cppreference;
Static data members are not associated with any object. They exist even if no objects of the class have been defined. If the static member is declared
thread_local
(since C++11), there is one such object per thread. Otherwise, there is only one instance of the static data member in the entire program, with static storage duration.