Search code examples
c++stdstringcurly-braces

Curly Brace Initialisation with std::string


I have been using curly brace initialisation more and more recently. Although I found a difference to round bracket initialisation in this case and I was wondering why.

If I do:

const std::string s(5, '=');
std::cout << s << std::endl;

I get:

=====

This is what I expect. But if I do:

const std::string s{5, '='};
std::cout << s << std::endl;

I get:

=

Why is this?

Edit: For the benefit for anyone that sees this. There is an unprintable character before the = in the second output. It just doesn't show on stackoverflow. Looks like:

enter image description here


Solution

  • This

    const std::string s(5, '=');
    

    uses the constructor taking a count and the character, ch (as well as an allocator):

    constexpr basic_string( size_type count, CharT ch,
                            const Allocator& alloc = Allocator() );
    

    But

    const std::string s{5, '='};
    

    uses

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

    which means that 5 will be converted to a char and your string will therefore have the size 2. The first character will have the value 5 and the other will be =.