In C++11 I declare the following union:
union U4 {
char c;
int i;
static int si;
};
When I compile this code with g++ 4.7.0 using -std=c++11 -pedantic-errors, I get the following errors (with minor editing):
error: local class ‘union U4’ shall not have static data member ‘int U4::si’ [-fpermissive]
error: ‘U4::si’ may not be static because it is a member of a union
The FDIS (N3242) does not explicitly allow static data members of named unions, as far as I can see. But I also don't see where the FDIS disallows static data members of named unions either The FDIS does repeatedly refer to what can be done with "non-static data members" [section 9.5 paragraph 1]. By contrast, that suggests the standard permits static data members of unions.
I don't have any use in mind for a static data member of a union. If I needed it I could probably get a close enough effect with a class containing an anonymous union. I'm just trying to understand the intent of the standard.
Thanks for the help.
Yes this is allowed. Section 9 of the Standard uses the word class
for classes, structs and unions, unless it explicitly mentions so otherwise. The only restrictions on static union members are for local unions (9.4.2/5) and for anonymous unions (9.5/5).
#include <iostream>
union Test
{
static int s;
};
int Test::s;
int main()
{
Test::s = 1;
std::cout << Test::s;
}
Output on LiveWorkSpace. Note that it compiles on Clang 3.2 but not on gcc 4.8.0 or Intel 13.0.1. It appears this is a gcc/Intel bug.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With