legends2k
legends2k

Reputation: 32884

Is this output valid or a compiler bug?

#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.

Upvotes: 0

Views: 112

Answers (1)

Andy Prowl
Andy Prowl

Reputation: 126422

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.

Upvotes: 7

Related Questions