Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

=====

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading