3
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?

MaxHeap
  • 1,138
  • 2
  • 11
  • 20

2 Answers2

5

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.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
2

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.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
  • 1
    Actually there could be difference, in the second case compiler may have to call `strlen` or something like that to realize that string is empty. It could be optimized but there is a good chance that it would not. – Slava Jan 25 '17 at 18:52
  • 1
    @Slava - On the contrary, [there is an extremely high chance](http://stackoverflow.com/a/11639305/597607) that it will be optimized. – Bo Persson Jan 25 '17 at 19:17