omegasbk
omegasbk

Reputation: 906

Initializing a C++11 string with {}

What is the difference between initializing a string with:

std::string testString = "Test";

and

std::string testString{"Test"};

Is this only syntactic sugar thing or there actually are some performance related differences?

Upvotes: 2

Views: 560

Answers (4)

user1832484
user1832484

Reputation: 371

I found a clear answer in Herb Sutter

https://herbsutter.com/2013/05/09/gotw-1-solution/

Upvotes: 0

Victor Dyachenko
Victor Dyachenko

Reputation: 1401

There is no difference in this particular case. But try

std::string s1(1, '0'); // calls string(size_type , char )
std::string s2{1, '0'}; // calls string(std::initializer_list<char> )

assert(s1.length() == 1 && s1[0] == '0');
assert(s2.length() == 2 && s2[0] == '\x1');

or with std::vector

std::vector<int> v1(1); // calls vector(size_type )
std::vector<int> v2{1}; // calls vector(std::initializer_list<int> )

assert(v1.size() == 1 && v1[0] == 0);
assert(v2.size() == 1 && v2[0] == 1);

Upvotes: 2

Kemal G&#252;ler
Kemal G&#252;ler

Reputation: 614

There is no difference between them.

First declaration is preferred in most projects due to the syntax highlighting.

Upvotes: 0

Curious
Curious

Reputation: 21510

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

Upvotes: 4

Related Questions