gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 16:39:58 26 4
gpt4 key购买 nike

最小代码示例:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com