Answer the question
In order to leave comments, you need to log in
Why is the maximum size of a std::string object 4611686018427387897?
In this piece of code, I'm printing out the maximum length of a std::string object:
string s;
cout<<s.max_size()<<endl;
cout << INT_MAX << endl;
cout<<LLONG_MAX<<endl;
4611686018427387897
2147483647
9223372036854775807
Answer the question
In order to leave comments, you need to log in
Well, it's just that the creators of the library hardcoded exactly this number.
This construction returns different values, depending on the compiler, bitness, operating system.
This is 2^62-7. Why 2^62? Maybe for some reason your system can't address more than 62 bits. Maybe the system uses 2 bits for something. Why -7? You need to store the length somewhere else, you need to leave room for the null character at the end, and you need to leave the std::string::npos index untouched - this value is used to indicate "non-existent index". The exact meaning depends on what the programmers of the standard library have done there.
In any case, this value is many, many orders of magnitude larger than any practically possible string length. Well, you can't allocate 4 exobytes of memory.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question