'Is it legal to define an anonymous struct?
Is the following code legal?:
struct
{
int x;
};
This code simply defines an unnamed structure. I do not intend to create objects of this type, nor do I need this structure in any other way. It simply appears in the source as a side effect of some complex macro expansion.
Useless though it is, I see no problem with it. Just another piece of code that can be compiled and then optimized out completely.
However, in the real world the outcome is quite different from my expectations:
GCC 8.3 reports an error:
error: abstract declarator '<unnamed struct>' used as declaration
Clang 8.0.0 reports an error too:
error: anonymous structs and classes must be class members
warning: declaration does not declare anything [-Wmissing-declarations]
Only MSVC 2017 sees no problem with such source.
So, the question is: who's right? Is there a relevant quote from the Standard that explicitly forbids such declarations?
Edit:
The project uses C++11. But the error messages are the same for C++98, C++11 and C++17.
Solution 1:[1]
No, it is not allowed. GCC and Clang are right.
Per [dcl.dcl]/3 (7 Declarations) in N3337 (C++11 final draft), a class declaration must introduce at one name to the program. For example, the following are invalid:
enum { };
typedef class { };
(Note: this isn't unique to C++11. In N4140 (C++14 final draft) it is [dcl.dcl]/5 (7 Declarations). In N4659 (C++17 final draft) it is [dcl.dcl]/5 (10 Declarations).)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |