【问题标题】:Aggregate Initialization of struct with dependent fields [duplicate]具有依赖字段的结构的聚合初始化[重复]
【发布时间】:2019-01-11 01:24:40
【问题描述】:

以下行为是否合法?

#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

【问题讨论】:

  • 在初始化时,instance 尚未创建,因此您无法引用其中的字段。

标签: c++ language-lawyer


【解决方案1】:

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

#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

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

【讨论】:

    猜你喜欢
    • 2016-06-23
    • 2019-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多