Why are data assigned without creating an additional copy in the initialization list?

Parashift explains the initialization lists well, but does not explain why an additional copy of the variable is created before the assignment in the ctor package, but no additional copy is created when assigned through the initialization list.
I even came across advice on using ++ i instead of i ++, because the first avoids creating a temporary self before the appointment. Same for POD assigned in ctor package? Is a temporary variable created before the assignment happens?

In other words, why does the compiler need to create an additional copy of the variable? Why can't he just assign the variable directly?
Why?

+5
source share
3 answers

Consider the following:

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

struct X {
    C member;

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

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

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

First, the constructor Cis called to create the data item member. Then the body is executed X, the second, temporary object Cis created and assigned member, then the temporary is destroyed.


Note that this applies only to types that are initialized automatically. If it memberhad the type intor type of the POD class (as an example), it would be uninitialized when the constructor body is introduced X.

, ; . .

+3

( "++ i" vs "i ++" ):

. , ( ). - . , , ( ) -. , , , ( , -).

+2

ctor body, .

Because the assignment follows initialization. In other words, assignment is optional, but initialization is required. You will not notice much difference for POD. But the same is true for custom data types.

tips for using ++ i instead of i ++

Again for POD, this is not a big deal. But for custom classes i++creates a temporary copy. Therefore, it is better to use ++i.

struct A {
  A operator ++ (int)  // example of i++
  {
    A temp = *this;
    this->value ++;
    return temp;    // makes 2 copies "temp" and return value
  }
  A& operator ++ ()  // example of ++i
  {
    this->value ++;
    return *this;  // no copy
  }
};
+2
source

All Articles