Search code examples
c++declarationlanguage-lawyervariable-initialization

Does the order of automatic variables creation correspond to the order of declaration?


Given:

void foo()
{
    std::vector<int> v1;
    std::vector<int> v2;
}

Is it guaranteed that v1 is constructed before v2, or is the order not defined? I can't find the answer in the standard (even though I know it's there somewhere).


Solution

  • Assuming no optimization takes place then yes, this is covered by the draft C++ standard in section 1.9 Program execution paragraph 14:

    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.8

    In reality the implementation is only obligated to emulate the observable behavior, which is called the as-if rule which is covered in paragraph 1 which says(emphasis mine):

    The semantic descriptions in this International Standard define a parameterized nondeterministic abstract machine. This International Standard places no requirement on the structure of conforming implementations. In particular, they need not copy or emulate the structure of the abstract machine. Rather, conforming implementations are required to emulate (only) the observable behavior of the abstract machine as explained below.5

    footnote 5 says:

    This provision is sometimes called the “as-if” rule, because an implementation is free to disregard any requirement of this International Standard as long as the result is as if the requirement had been obeyed, as far as can be determined from the observable behavior of the program. For instance, an actual implementation need not evaluate part of an expression if it can deduce that its value is not used and that no side effects affecting the observable behavior of the program are produced.