Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between "" and {} for initializing an empty string?

string a = "";
string b = {};

I couldn't really find a good reference explaining the difference between them. Does a compiler see them differently? Then, why?

like image 738
MaxHeap Avatar asked Nov 19 '25 03:11

MaxHeap


2 Answers

a is constructed using copy initialisation.

b is constructed using copy list initialisation.

For a std::string the compiler will produce the same thing; a zero length string.

But the mechanism by which the string is constructed may well be different - a compiler, conceptually at least, will have to traverse the anonymous temporary const char[] passed to construct a.

For other types there may be differences; research the two terms above for more details.

like image 130
Bathsheba Avatar answered Nov 20 '25 16:11

Bathsheba


In this case, no difference.

string b = {};

initializes the string with the type's default value, which is an empty string.

string a = "";

initializes the string with a specific value, which happens to also be an empty string.

Note that just doing string c; would also create an empty string.

like image 26
Bo Persson Avatar answered Nov 20 '25 17:11

Bo Persson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!