Search code examples
c++language-lawyerc++17operator-precedence

Is the order of evaluation for initialization lists in constructors fixed?


I was under the impression that the following is prone to leaks

class Something {
    std::unique_ptr<A> a;
    std::unique_ptr<int> b{new int{3}};
    std::unique_ptr<C> c;
public:
    Something() : a{new A{}}, c{new C{}} {};
};

if the order of evaluation was the following

  1. new A{}
  2. new int{3}
  3. new C{}
  4. a{}
  5. b{}
  6. c{}

I was taking a look at the new C++17 feature (http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0145r3.pdf) that fixes order of evaluation faults in previous versions of C++, but it only seems to talk about function argument evaluations.

I took a look at the cppreference documentation on order of evaluation (http://en.cppreference.com/w/cpp/language/eval_order) and it does not seem to mention this either.

Does the above have a well defined order of evaluation? (either now in C++17 or in previous versions of C++)


Solution

  • No, that order is not allowed; the language isn't that insane.

    These are completely distinct full-expressions, so it's controlled by [intro.execution]/16:

    Every value computation and side effect associated with a full-expression is sequenced before every value computation and side effect associated with the next full-expression to be evaluated.