void f()
{
auto x = func();
int y = func();
auto z = f1() * f2() + static_cast<int>(f3());
}
I believe it should be defined that call to the func
will always happened first, before memory allocation for x
, for the case with auto
, but couldn't found info about it.
Is it so?
And is it defined for the case when type is explicitly written?
Evaluation of the initialization expression (func()
or f1() * f2() + static_cast<int>(f3())
) definitely happens only when the particular line of code is reached.1
Memory for the variable may be obtained (aka "allocation") at any time earlier... however there's no way to use that memory prior to the definition because until the definition is reached there's no way to name that memory. The variable name is introduced into scope by the definition.
The lifetime of the object living in the variable doesn't begin until the initializer is fully evaluated and placed2 into the new object. See [basic.life]
:
The lifetime of an object of type
T
begins when:
- storage with the proper alignment and size for type
T
is obtained, and- its initialization (if any) is complete (including vacuous initialization)
If the address of the variable is never taken, the variable might not need any memory at all (it could fit in a CPU register for its entire lifetime).
1 Well, under the as-if rule, the compiler can move it around so long as you can't tell the difference. Unless you have undefined behavior such as a data race, it will always act exactly like the computation is done when reaching that line of code.
2 For the copy-initialization syntax used in the question, old versions of C++ generally required a copy or move, while newer versions mandate in-place construction via copy-elision.