0
#include <iostream>
#include <string>

int main(int argc, char *argv[])
{
    std::string s = {123};
    std::cout << s << std::endl;
}

Why does this program print { as an output? Is it a bug in the underlying lexer that it only prints the preceeding {?

I compiled this with g++ 4.8.1 (with no errors or warnings). MSVC doesn't compile this complaining that string isn't an aggregate type.

legends2k
  • 31,634
  • 25
  • 118
  • 222

1 Answers1

7

You are list-initializing a string with an array of characters. 123 is the ASCII code of {. There is no compiler bug.

The constructor you are invoking is the initalizer-list constructor of std::string (see here for a reference), as specified by paragraph 21.4.2/15 of the C++11 Standard:

basic_string(std::initializer_list<CharT> init, 
             const Allocator& alloc = Allocator());

Effects: Same as basic_string(il.begin(), il.end(), a).

MSVC does not support list-initialization, which is why you are getting the message complaining about the fact that string is not an aggregate.

Andy Prowl
  • 124,023
  • 23
  • 387
  • 451