静态数据成员的类内初始化 [英] In-class initialization of static data members
问题描述
在C ++中,可能无法在类主体中初始化 static
成员,但以下情况除外:
In C++, static
members may not be initialized in the class body with these exceptions:
- $ b
-
静态
整数类型的成员可以constexpr
文字类型必须的
-
静态
成员
static
members ofconst
integral type can bestatic
members ofconstexpr
literal type must be
您能解释这些例外的原因吗?
Can you explain why these exceptions?
此外,这适用于:
即使
const static
数据成员在类主体中初始化,该成员通常应在类定义之外定义。
Even if a
const static
data member is initialized in the class body, that member ordinarily should be defined outside the class definition.
我一点都不明白。
只是试图在这里获得一些直觉。
Just trying to get some intuitions here.
推荐答案
为什么在类定义中会有一个初始化器?
Why can there be an initializer in the class definition?
关于 const
和 constexpr
静态数据成员:
[class.static.data] / 3
[class.static.data]/3
[注意:在这两种情况下,成员都可能以常量表达式出现。 —尾注]
[ Note: In both these cases, the member may appear in constant expressions. — end note ]
即使用初始化程序,您可以在常量表达式中使用它们,例如
I.e. with an initializer, you may use them in constant expressions, e.g.
struct s
{
static std::size_t const len = 10;
int arr[len];
};
std::size_t const s::len;
如果 len
未在类定义,编译器不容易在下一行中知道其值来定义 arr
的长度。
If len
wasn't initialized in the class definition, the compiler couldn't easily know its value in the next line to define the length of arr
.
有人可能会争论在类定义中允许非 const
,非 constexpr
静态数据成员的初始化程序,但这可能会干扰初始化顺序:
One could argue about allowing initializers for of non-const
, non-constexpr
static data members in the class definition, but this could interfere with the initialization order:
[basic.start.init] / 2
[basic.start.init]/2
显式专门的类模板静态数据成员的定义已命令初始化。其他类模板静态数据成员(即,隐式或显式实例化的专长)具有无序初始化。 具有静态存储持续时间的其他非局部变量已对初始化进行了排序。
即包括初始化程序的定义很重要。非本地对象的(动态)初始化顺序仅在转换单元内定义,这是为什么必须为非 const
包括初始化器的定义的另一个原因,非 constexpr
静态数据成员。
That is, the order of the definitions including initializers is important. The order of (dynamic) initialization of non-local objects is only defined within a translation unit, this is another reason why there has to be a definition including initializer for non-const
, non-constexpr
static data members.
重点是什么
这已在IMO评论中得到了回答。您可能需要添加ODR,即作为具有外部链接的名称,必须(仅)在一个转换单元(如果使用了ODR)中定义静态数据成员。程序员需要选择此翻译单元。
This has already been answered in the comments IMO. You might want to add the ODR, that is, as a name with external linkage, the static data member must (only) be defined in one translation unit (if it's ODR-used). It's up to the programmer to choose this translation unit.
这篇关于静态数据成员的类内初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!