简体   繁体   中英

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

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.

Yes and no. It's guaranteed that the observed behavior is equivalent to them being constructed in the order in which they are declared, but due to optimizations they might not be constructed at all.

Yes, objects are always constructed in the order that they are defined It's the same if you do it on one line:

    std::vector<int> v1, v2;

or if they are members of a class:

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

The order of construction is the order of definition, and the order of destruction is the opposite.

There's no need to invoke the as-if rule here. Whatever meaning and behavior is guaranteed by construction of an object, you will get. Whatever is not guaranteed, never was part of the language or the program in the first place.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM