string
sEach class defines how objects of its type can be initialized. A class may define many different ways to initialize objects of its type. Each way must be distinguished from the others either by the number of initializers that we supply, or by the types of those initializers. Table 3.1 lists the most common ways to initialize string
s. Some examples:
string s1; // default initialization; s1 is the empty string
string s2 = s1; // s2 is a copy of s1
string s3 = "hiya"; // s3 is a copy of the string literal
string s4(10, 'c'), // s4 is cccccccccc
We can default initialize a string
(§ 2.2.1, p. 44), which creates an empty string
; that is, a string
with no characters. When we supply a string literal (§ 2.1.3, p. 39), the characters from that literal—up to but not including the null character at the end of the literal—are copied into the newly created string
. When we supply a count and a character, the string
contains that many copies of the given character.
In § 2.2.1 (p. 43) we saw that C++ has several different forms of initialization. Using string
s, we can start to understand how these forms differ from one another. 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. Otherwise, when we omit the =
, we use direct initialization.
When we have a single initializer, we can use either the direct or copy form of initialization. When we initialize a variable from more than one value, such as in the initialization of s4
above, we must use the direct form of initialization:
string s5 = "hiya"; // copy initialization
string s6("hiya"); // direct initialization
string s7(10, 'c'), // direct initialization; s7 is cccccccccc
When we want to use several values, we can indirectly use the copy form of initialization by explicitly creating a (temporary) object to copy:
string s8 = string(10, 'c'), // copy initialization; s8 is cccccccccc
The initializer 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'), // temp is cccccccccc
string s8 = temp; // copy temp into s8
Although the code used to initialize s8
is legal, it is less readable and offers no compensating advantage over the way we initialized s7
.