首页 > 解决方案 > 具有依赖字段的结构的聚合初始化

问题描述

进行以下操作是否合法?

#include <iostream>

struct Foo
{
    int bar;
    int baz;
};

int main()
{
    Foo instance = { 5, instance.bar };
    std::cout << instance.baz << std::endl;
}

我认为这不是因为据我所知初始化的顺序是未指定的,并且该bar字段可以在baz.

我对吗?

https://coliru.stacked-crooked.com/a/ea97713515dd0687

标签: c++language-lawyer

解决方案


如果你喜欢你的难题,这真的会烤你的面条:

#include <iostream>

struct Foo
{
    int bar=0;
    int baz=1;
};

const int cool(const Foo& f) 
{
    std::cout << "Bar: " << f.bar << " Baz: " << f.baz << std::endl;
    return f.bar;
}

int main()
{
    Foo instance = { 5, cool(instance) };
    std::cout << instance.baz << std::endl;
}

以前的海报正确引用了什么:c++ std Draft doc

...与给定元素相关的所有值计算和副作用都按顺序排列在其后面的任何元素之前。


推荐阅读