Compiler error with C++17 static inline members

人盡茶涼 提交于 2021-02-04 19:20:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!