问题
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;
}
It works fine.
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.
However this works:
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
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?
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:
error: ISO C++ forbids in-class initialization of non-const static member 'Foo::a'
See Online GDB
回答1:
is this a bug?
This is certainly a bug in MSVC.
As per class.static.data/3:
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.
It works fine using GCC and Clang.
来源:https://stackoverflow.com/questions/51276050/compiler-error-with-c17-static-inline-members