2

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?

4 Answers 4

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

I'm still confused. Is constructor and copy constructor essentially the same ? How does uniform initialization and initiallizer list work? How's the const char* object ended up with?
2

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);

Comments

0

There is no difference between them.

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

5 Comments

What sort of syntax highlighting is missing in the second one?
@Curious aren't you ;) I think it's more readable. I don't see any missing syntax highlighting either.
There is nothing missing @Curious. I just want to say first one is more readable.
your opinion on which is more readable isn't really relevant. Saying that it's preferred in most projects is not even clear that it's your opinion.
First declaration is preferred, because it is more readable. That is not my opinion. All my friends use first declaration on their projects. Is it relevant?
0

I found a clear answer in Herb Sutter

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.