Quick Q: Initializing a C++11 string with {}

Quick A: It calls the initializer_list constructor that has the same effect in this case.

Recnetly on SO:

Initializing a C++11 string with {}

The {} initialization syntax is known as the uniform initialization syntax, it has a few key differences, but in your code as is they both do the same thing - construct a std::string object from the string literal "Test"

Initializing an object with an assignment is essentially the same as putting the right hand side in parentheses and constructing the object. For example the below two are the same

T obj = a;
T obj(a);

So you should be asking yourself, what is the difference between constructing a string object the following two ways

std::string{"Test"};
std::string("Test");

And the answer is that both the constructions above are the same and call the same constructor for std::string

For more on uniform initialization see https://softwareengineering.stackexchange.com/questions/133688/is-c11-uniform-initialization-a-replacement-for-the-old-style-syntax

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.