Parashift explains initialization lists well, but does not explain why an extra copy of a variable is created before assignment in the ctor body, but no extra copy is created when assigned through an initialization list.
I’ve even come across advice of using ++i instead of i++ because the former avoids creation of a temporary i before assignment. Is it the same for POD’s assigned in a ctor body? A temp variable gets created before the assignment happens?
To put it another way, why does the compiler need to create an extra copy of a variable? Why can’t it just assign the variable directly?
Why?
Consider the following:
The
X()constructor is the same as if you had said:First, the
Cconstructor is called to construct thememberdata member. Then the body ofXis executed, a second, temporaryCobject is created and assigned tomember, then the temporary is destroyed.Note that this is only the case for types that are initialized automatically. If
memberwas of typeintor of a POD class type (as examples), it would be uninitalized when the body of theXconstructor is entered.For such types it doesn’t really matter from a performance standpoint whether you initialize the data member in the initialization list or assign to the data member in the body of the constructor; the difference is entirely stylistic. Where possible, the initialization list should still be preferred for the sake of consistency.