6

As seen on ideone:

cout << string(50, 'x'); // xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx cout << string{50, 'x'}; // 2x 

WAT??

I have figured out that 50 is ASCII '2', so:

cout << static_cast<int>('2'); // 50 cout << static_cast<char>(50); // 2 

But that's as far as I've got.

Does this lead to a solid argument against C++11 initializers?

3
  • 2
    the initializer_list constructor of string takes a list of characters, that's why. Commented Nov 21, 2014 at 14:40
  • 1
    (here's the relevant documentation.) Commented Nov 21, 2014 at 14:42
  • 2
    To answer the last line: No, it doesn't. It just means you have to understand what they do. Commented Nov 21, 2014 at 14:54

1 Answer 1

8

When you do string { 50, 'x' } you're essentially initializing the string with a list of characters.

On the other hand, string(50, 'x') calls a 2 argument constructor, which is defined to repeat the character x 50 times. The reason why string { 50, 'x' } doesn't pick the constructor is that it could be ambiguous. What if you had a three parameter constructor as well? If the type has an initializer_list constructor, it will be picked when you use { ... } for initialization.

Basically you need to be aware of the constructors your type has. The initializer_list constructor will always have a precedence to avoid ambiguity.

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

1 Comment

Shouldn't {50, 'x'} not be convertible to std::initializer_list<char> due to the narrowing conversion?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.