Does C++11 allow non-anonymous unions to contain static data members?

試著忘記壹切 提交于 2021-02-07 13:09:02

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/15996333/does-c11-allow-non-anonymous-unions-to-contain-static-data-members

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