内联静态成员变量

编程入门 行业动态 更新时间:2024-10-26 21:23:17
本文介绍了内联静态成员变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 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() {} };

更多推荐

内联静态成员变量

本文发布于:2023-11-14 03:09:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1586054.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:内联   变量   静态   成员

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!