Anonymous aggregation rules

Consider the following:

#include <type_traits> struct MyType { int val; MyType(void) = default; MyType(int v) : val(v) {} }; static_assert(std::is_standard_layout<MyType>::value,"Implementation error!"); static_assert(std::is_trivial<MyType>::value,"Implementation error!"); static_assert(std::is_pod<MyType>::value,"Implementation error!"); struct Wrapper { struct { MyType t; }; }; 

MSVC, Clang and Intel C ++ will compile all this. But g++4.9 foo.cpp -std=c++11 tells me:

14: error: member 'MyType Wrapper :: <anonymous struct> :: t' with a constructor that is not allowed in an anonymous aggregate
MyType t;
^
Compilation error

Note that static_assert ensures that MyType is a standard layout , a trivial type , and also actually a POD (note that after C ++ 11, PODs are allowed to have constructors).


I could not find anything authoritative in what types are allowed inside anonymous structures. What I found (mainly here on SO) indicates that being a POD type is sufficient. This is apparently not the case.

My question is: If the POD type is actually insufficient for an anonymous structure, what is enough? Or maybe, since GCC is different from all other compilers, is this a problem with GCC?

+5
source share
1 answer

Regarding standards, anonymous structures are a function of C. They are not allowed by any C ++ standard.

I could not find the detailed gcc documentation about my extension to provide this function in C ++. What I found is here , but this page only describes the extension for C (prior to C11 this function was not standard).

My question is: if the POD type is actually insufficient for an anonymous structure,

It really seems insufficient. The error message clearly explains that having a (non-trivial) constructor disqualifies the class as an anonymous aggregate (structure). POD would guarantee this only until C ++ 11.

Since there is little documentation for the extension, and since anonymous structures are a function of C, I am tempted to assume that any such aggregate should not use the capabilities of C ++. I believe that the definition of POD for pre-C ++ 11 satisfies this requirement.

A quick test seems to be consistent with my hypothesis. If you remove the constructor, the program compiles with the extension enabled. If you name a member of the structure (a promotion type that needs to be anonymous), the program will be well formed by standard C ++, and also compiled.

Or maybe, since GCC is different from all other compilers, is this a problem with GCC?

Since they implemented them, it is possible that this is not a problem with them. This can be a problem for those who want to compile without modification, a non-standard program written for another compiler. This is a problem with non-standard language features.

+5
source

All Articles