Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11: string(50, 'x') versus string{50, 'x'}

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?

like image 784
P i Avatar asked Nov 21 '14 14:11

P i


People also ask

What does string resize do?

It resizes the string such that string contains k characters. If k is shorter than the length of the string, string length shortened to the length specified by k, removing all the characters beyond k. If k is larger than the length of the string, string length extended to the length specified by k.

How do you determine a string size?

You can get the length of a string object by using a size() function or a length() function.

How can I compare two strings in C++?

In order to compare two strings, we can use String's strcmp() function. The strcmp() function is a C library function used to compare two strings in a lexicographical manner. The function returns 0 if both the strings are equal or the same. The input string has to be a char array of C-style string.

What is the difference between char * and char []?

What is the difference between char and char*? char[] is a character array whereas char* is a pointer reference. char[] is a specific section of memory in which we can do things like indexing, whereas char* is the pointer that points to the memory location.


1 Answers

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.

like image 199
Jakub Arnold Avatar answered Sep 23 '22 16:09

Jakub Arnold