C++ 之 Direct and Copy Forms of Initialization

时间:2021-07-05 08:51:56

Extraction from C++ Primer 5th. Editioin 3.2.1

C++ has several different forms of initialization, we should understand how these forms differ from one aother.

When we initialize a variable using =, we are asking the compiler to copy initialize the object by copying the initializer on the right-hand side into the object being created.

Ohterwise when we omit the =, we use direct intialization.When we have a single intializer, we use either the direct or copy form of intialization. When we intialize a variable from more than one value, such as:

string s4(, 'c');

we must use the direct form of initialization.

when we want to use several values, we can indirectly use the copy form of intialization be explicitly creating a (temporary) object to copy:

string s8=string(, 'c');    //copy initialization

The intializer of s8——string(10, 'c')——creates a string of the given size and character value and then copies that value into s8. it is as if we had written

string temp(, 'c');
string s8=temp;

Although the used to intialize s8 is legal, it is less readable and offers no compensating advantage over the way we intilize s4.