内联静态成员变量 [英] inline static member variable
问题描述
struct sa
{
struct sb { int a = 123;};
inline static sb b;
};
上面的代码生成错误:
main.cpp:25:20: error: default member initializer for ‘sa::sb::a’ required before the end of its enclosing class
inline static sb b;
^
main.cpp:24:21: note: defined here
struct sb { int a = 123;};
^~~~~~
删除内联
关键字或默认成员初始化程序起作用。但是仅仅从输出中,我不理解为什么这种用法是错误的。
Removing the inline
keyword or the default member initializer works. But just from the output, I don't understand why this usage is wrong.
推荐答案
我认为这段代码是正确的,应该被接受;为了避免核心问题1397 。
I think this code is correct and should be accepted; gcc and clang are erring on the side of caution in order to avoid the defect of Core Issue 1397.
该问题规定,如果NSDMI(非静态数据成员初始化器)导致程序格式错误,类的默认默认构造函数。
That issue ruled that a program is ill-formed if a NSDMI (non-static data member initializer) causes the class's defaulted default constructor to be generated.
但是您的代码却不这样做。 NSDMI只是整数文字。导致此问题的示例的代码如 int a =((sa(),123));
However your code doesn't do that. The NSDMI is just an integer literal. The example that prompted this issue had code like int a = ( (sa(), 123) );
我猜可能正在发生:该标准还说,在处理NSDMI时,应该将类 sa
视为完整类。因此,也许编译器会推迟NSDMI处理,直到达到 sa
的大括号为止。然后标记错误,因为内联静态sb b;
会生成 sb :: sb()
。
What I guess might be happening is: The standard also says that , when processing the NSDMI, the class sa
should be treated as complete. So perhaps the compilers are deferring the NSDMI processing until after the closing brace of sa
is reached; and then flagging the error because inline static sb b;
would generate sb::sb()
.
可能该标准仍然存在缺陷,直到现在为止还没有人想到您的示例。
Possibly the standard is still defective and nobody thought of your example until now.
作为一种解决方法,您可以明确提供麻烦的构造函数:
As a workaround you can explicitly provide the troublesome constructor:
struct sb { int a = 123; sb() {} };
这篇关于内联静态成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!