微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C++ 中指定初始值设定项的未定义行为

如何解决C++ 中指定初始值设定项的未定义行为

在我尝试过的所有编译中都没有任何警告地接受以下 C++20 程序:

struct A { const int & x = z; int y = x; int z; };

int main()
{
    return A{.z=3}.y;
}

https://gcc.godbolt.org/z/nqb95zb7c

但是每个程序都会返回一些任意值。假设这是未定义的行为是否正确?

解决方法

成员按照它们在类定义中出现的顺序进行初始化,因此指定的初始化器不是那么相关,还有这个

struct A { 
    const int & x = z; 
    int y = x;           // <- read of indeterminate value !
    int z = 42;          // <- doesn't really matter because y is initialized before ! 
};

int main() {
    return A{}.y;
}

出于同样的原因未定义。


另见来自 cppreference 的示例:

struct A {
  string str;
  int n = 42;
  int m = -1;
};
A{.m=21}  // Initializes str with {},which calls the default constructor
          // then initializes n with = 42
          // then initializes m with = 21

这个例子实际上是为了说明别的东西,但它也展示了成员是如何按顺序初始化的。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。