Search code examples
c++initialization-list

Why does data get assigned without an extra copy being created, in an initialization list?


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?


Solution

  • Consider the following:

    struct C { 
        C() { /* construct the object */ }
    };
    
    struct X {
        C member;
    
        X() { member = C(); }
    };
    

    The X() constructor is the same as if you had said:

    X() : member() { member = C(); }
    

    First, the C constructor is called to construct the member data member. Then the body of X is executed, a second, temporary C object is created and assigned to member, then the temporary is destroyed.


    Note that this is only the case for types that are initialized automatically. If member was of type int or of a POD class type (as examples), it would be uninitalized when the body of the X constructor 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.