C++11 "In class initialization"功能不适用于 union

标签 c++ c++11 unions in-class-initialization

最小代码示例:

struct B { 
  union U {
    struct S {} s;
    int i = 100;
  }
  u;  
};

现在,如果我们声明一个 B obj;,那么 obj.u.i 会被分配一个垃圾值而不是 100。查看demo here . (垃圾值因优化标志等而异)。

“类内初始化”功能是否应该与 union 一起使用。

  • 如果是,那么正确的语法是什么?或者这是一个 g++ 错误?
  • 如果不是,那么 int i = 100; 做什么?

最佳答案

这看起来像一个 GCC 错误。标准说 (9.5p2):

At most one non-static data member of a union may have a brace-or-equal-initializer.

否则,规则与普通类(class)相同。

编辑:此外,12.6.2p8:

In a non-delegating constructor, if a given non-static data member or base class is not designated by a mem-initializer-id (including the case where there is no mem-initializer-list because the constructor has no ctor-initializer) and the entity is not a virtual base class of an abstract class (10.4), then

  • if the entity is a non-static data member that has a brace-or-equal-initializer, the entity is initialized as specified in 8.5;
  • otherwise, if the entity is a variant member (9.5), no initialization is performed;
  • otherwise, the entity is default-initialized (8.5).

大概隐式定义的默认构造函数在这里很重要。 i 成员满足第一个要点中的条件,因此它像普通类成员一样被初始化。 s 成员与第二个要点匹配,因此未初始化。

关于C++11 "In class initialization"功能不适用于 union ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17790278/

相关文章:

c++ - C++ 中另一个带有闭包的抽象类问题

c++ - 将 ino sketch 转换为 C++ 类,无效使用非静态成员函数

c++ - C/C++ : is using the result of comparison as int really branchless?

c++ - "if (getline(fin, str)) {}"是否符合C++11标准?

c++ - 这种内存使用优化技术在 union 的情况下是否可行?

c++ - Union 在 OOP 中的使用

c - gcc、严格别名和通过 union 转换

c++ - 匿名结构作为返回类型

java - 如何以编程方式打开/关闭 Caps Lock、Scroll Lock 和 Num Lock

c++ - vector< vector<Point3f>> 中的最高值