-
Notifications
You must be signed in to change notification settings - Fork 1
1.3 Establishing a Default Value
Create a string with a default value.
You can create an empty string by default constructing it:
std::string empty;
There are three ways to initialize a string using a string literal: brace initialization, and direct and copy initialization.
std::string brace{"This uses brace initialization"};
std::string direct("This uses direct initialization");
std::string copy = "This uses copy initialization";
You can embed newlines in a string literal, thereby including the newlines in the string:
std::string multiline{"This is the first line
This is the second line"};
Note that all newlines between the quotation marks are included. The following string has four lines; the first and last are blank.
std::string four{"
This is the second line.
Here's the third line.
"};
Brace initialization is new with C++11, so you may not have that option. In that case, use direct or copy initialization. Refer to StackOverflow for details on direct and copy initialization. Direct initialization is preferred over copy initialization, at least as a matter of habit, because it is more efficient when the compiler cannot or does not elide the copy constructor.
You can determine whether a string is empty using std::string::empty()
, which returns a bool
. The default constructor creates an instance for which empty()
returns true
.
std::string
can hold null characters along with others. Brace initialization makes embedding them easier, but only if you care to create the string by a list of characters:
std::string embedded{'T', 'e', 's', 't', '\0', 's', 't', 'u', 'f', 'f'};
embedded
contains a null character between the Test
and stuff
.