C++ 之 Direct and Copy Forms of Initialization

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(10, '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(10, '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(10, '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.

posted @ 2016-08-20 23:59  Pat  阅读(245)  评论(0编辑  收藏  举报