使用内联静态成员而不是静态成员
我有一个以下结构:
#include <iostream>
struct Foo
{
static int a; // declaration
inline static int b = 10; // declaration and definition
};
int Foo::a = 10; // definition
int main()
{
std::cout << Foo::a << "\n"; // --> 10
std::cout << Foo::b << "\n"; // --> 10 (same result as Foo::b)
return 0;
}
使用内联静态
实现与static
使用时相同的目标是“易于”的。
使用static
上课的成员而不是inline static
成员是更可取的/必需的,是否有任何情况?
注意:当人们使用C ++ 14或更低标准时,有一个明显的情况。
I have a following struct:
#include <iostream>
struct Foo
{
static int a; // declaration
inline static int b = 10; // declaration and definition
};
int Foo::a = 10; // definition
int main()
{
std::cout << Foo::a << "\n"; // --> 10
std::cout << Foo::b << "\n"; // --> 10 (same result as Foo::b)
return 0;
}
It is "easier" to use inline static
to achieve same goal as when static
is used.
Is there any case when using static
members for class instead of inline static
members is more preferable/required?
Note : there is an obvious case when one uses C++14 or lower standard.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您尝试创建“状态枚举”,您会看到它。基本上,捕获一些数据并有几个类型的“命名常数”的类,您想将其编码为静态数据成员。要说明:
这将是不正确的,而这不会:
实时示例
原因是静态数据成员可能具有不完整的类型,但是初始化时必须完成。
与ConstexPR静态成员一起玩时,它自然会弹出。来C ++ 17,它们隐含地内联,因此,如果您想拥有它们,则您 将声明从定义中分解出来:
实时示例
这些是有效的常数,并且在恒定表达式中可用。但是它们不能在线定义为静态数据成员。由于
constexpr
,但在技术上仍然是内联数据成员,但并未定义内联(尽管请注意,在C ++ 17之前也是如此,但是无法在标题中定义常数以重新定义错误,因此它们本质上是无法使用的)。You'd see it if you ever try to create "stateful enums". Basically, classes that capture a little data and there is a handful of "named constants" of that type that you'd want to codify as static data members. To illustrate:
This will be ill-formed, whereas this will not:
Live example
The reason is that a static data member may have an incomplete type, but it must be complete when initialised.
It will naturally pop up when playing with constexpr static members. Come C++17, they are implicitly inline, so you'd have to break the declaration from definition if you want to have them:
Live example
Those are valid constant, and are usable in constant expressions. But they cannot be defined inline as static data members. They are still technically inline data members on account of being
constexpr
, but are not defined inline (mind though that it's true prior to C++17 too, but the constant cannot be defined in a header for redefinition errors, so they are essentially unusable).