Ordering in an initialization in C, C++

前端 未结 4 1233
日久生厌
日久生厌 2021-02-18 22:47

Consider the following initializations:

/* C, C++ */
int a[] = { f(), g() };
struct { int x, y } foo = { f(), g() };

/* C++ */
struct goo { goo(int x, int y);           


        
4条回答
  •  攒了一身酷
    2021-02-18 23:38

    In C++11, the relevant part is paragraph 4 of 8.5.4 List-initialization

    Within the initializer-list of a braced-init-list, the initializer-clauses, including any that result from pack expansions (14.5.3), are evaluated in the order in which they appear. That is, every value computation and side effect associated with a given initializer-clause is sequenced before every value computation and side effect associated with any initializer-clause that follows it in the comma-separated list of the initializer-list. [ Note: This evaluation ordering holds regardless of the semantics of the initialization; for example, it applies when the elements of the initializer-list are interpreted as arguments of a constructor call, even though ordinarily there are no sequencing constraints on the arguments of a call. — end note ]

    So the order of evaluation is left-to-right.

    However note that unfortunately, due to a bug since at least version 4.7.0, GCC evaluates in the opposite order, right-to-left. So if you get any unexpected results, this may be a reason.

提交回复
热议问题