C ++ 17静态内联成员的编译器错误 [英] Compiler error with C++17 static inline members
问题描述
我正在使用Microsoft Visual Studio 2017,从我所看到的来看,它确实支持C ++ 17静态内联类变量.我的问题是,如果我将所有成员统一化,则可以正常工作,但是在初始化某些成员时出现编译器错误.在下面的示例中:
I'm using Microsoft Visual Studio 2017, and from what I've seen it does support C++17 static inline class variables. My issue is that if I leave all members unitialised it works fine but I get a compiler error when initialising certain members. In the following example:
#include <iostream>
class Foo
{
public:
static inline int a;
static inline int b;
static inline int c;
};
int main()
{
Foo foo;
std::cout << foo.a; // Prints 0
std::cin.ignore();
return 0;
}
它工作正常.
在以下情况下,我会收到编译器错误:
In the following cases I get the compiler error:
class Foo
{public:
static inline int a = 7; // Initialise
static inline int b;
static inline int c;
}; //ErrorC1001 An internal error has occurred in the compiler.
class Foo
{public:
static inline int a = 7; // Initialise
static inline int b = 7; // Initialise
static inline int c;
}; //ErrorC1001 An internal error has occurred in the compiler.
class Foo
{public:
static inline int a = 7; // Initialise
static inline int b = 7; // Initialise
static inline int c = 7; // Initialise
}; // Initialise all three, no error. Works fine.
但这可行:
class Foo
{public:
static inline int a;
static inline int b = 7; // Initialise second
static inline int c;
}; // Does compile but doesn't initialise 'b' to 7, instead it is 0
因此,我认为初始化第一个成员需要初始化每个其他成员,但是只有在初始化第一个成员时才是这种情况.我花了很长时间才弄清楚为什么要发出此消息,这是一个错误吗?还是只有在初始化第一个静态成员时才需要初始化所有 static
inline
成员吗?
So I think that initialising the first member requires you initialise every single other member, however this is only the case if you initialise the very first member. It took me ages to figure out why it was giving this message, is this a bug? Or is there a strange requirement to initialise all static
inline
members only if you initialise the first one?
此外,我尝试使用onlinegdb.com上的 static
inline
成员,以C ++ 17进行编译,似乎不支持它,因为错误消息是:
Also, I've tried using the static
inline
member at onlinegdb.com, compiling in C++17, and it seems as though it doesn't support it, as the error message is:
错误:ISO C ++禁止非常量静态的类内初始化成员'Foo :: a'
error: ISO C++ forbids in-class initialization of non-const static member 'Foo::a'
请参见在线GDB
推荐答案
这是一个错误吗?
is this a bug?
这肯定是MSVC中的 bug .
This is certainly a bug in MSVC.
根据 class.static.data/3 :
可以在类定义中定义
inline
static
数据成员并可以指定 brace-or-相等初始化器 .
An
inline
static
data member may be defined in the class definition and may specify a brace-or-equal-initializer.
因此,可以使用 默认成员初始化 用于非常量静态内联类成员变量.
Thus, it is acceptable to have default member initialization for non-const static inline class member variables.