Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

order of evaluation of arguments to a constructor [duplicate]

Tags:

c++

c++11

Say I have this class:

struct A
{
  A(int, int, int) {}
};

and I initialize it like this:

A{ a(), b(), c() };

Where the functions a(), b() and c() all return int. Should a() be called before b() and b() before c()?

I am mystified by the following paragraph from the standard (8.5.4 [dcl.init.list] p4):

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 ]

According to the quote, the functions would be called in order they appear, but when I've tested this with my compiler (g++-4.8.1), it did not hold. Have I misunderstood something?

like image 417
user1095108 Avatar asked Feb 16 '23 02:02

user1095108


1 Answers

This is a bug in GCC (thanks to Casey for the link). The paragraph you quoted applies in general to list initialization, where the terms are defined pretty clearly in paragraph 8.5.4/1:

List-initialization is initialization of an object or reference from a braced-init-list. Such an initializer is called an initializer list, and the comma-separated initializer-clauses of the list are called the elements of the initializer list.

There is no reason to believe this should apply only to the invocation of an initializer list constructor. Also, the note in the paragraph you quoted clarifies that:

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.

like image 134
Andy Prowl Avatar answered Mar 08 '23 13:03

Andy Prowl