I know that I can use initialization list to fill a string. I also know that I can use a constructor with a count parameterer to insert null characters into string. But when I combine both... strange things happen.
It looks that the compiler makes some implicit promotion from int to initializer_list or allocator. But I don't know why it doesn't give me any warning and why it makes it implicit.
Could you explain to me what happens with strings s6, and s7?
#include <iostream>
#include <string>
using namespace std;
class A{
};
int main() {
// string::string(charT const* s)
string s1("12345");
// 5 - because constructor takes into account null-terminated character
cout << s1.size() << endl;
// string::string(charT const* s, size_type count)
string s2("12345",3);
// 3 - because the length of the string is taken from count parameter.
cout << s2.size()<<endl;
string s3("12345",5);
// 5 - because the length of the string is taken from count, parameter.
cout << s3.size()<<endl;
// string(std::initializer_list<charT> ilist)
string s4({'1','2','3','4','5'});
// 5 - because string is built from the contents of the initializer list init.
cout << s4.size()<<endl;
// basic_string( std::initializer_list<CharT> init,const Allocator& alloc = Allocator() );
// doesn't compile, no known conversion for argument 2 from 'A' to 'const std::allocator<char>&'
//string s5({'1','2','3','4','5'},A());
//cout << s5.size()<<endl;
// basic_string( std::initializer_list<CharT> init,const Allocator& alloc = Allocator() );
string s6({'1','2','3','4','5'},3);
// 2 - why this compiles (with no warning) and what this result means?
cout << s6.size() << endl;
string s7({'1','2','3','4','5'},5);
// 0 - why this compiles (with no warning) and what this result means?
cout << s7.size()<<endl;
return 0;
}
Aucun commentaire:
Enregistrer un commentaire