I have some questions about strings in C++:
#include <iostream>
#include <string>
void* operator new(std::size_t count) {
std::cout << count << " bytes allocation" << std::endl;
return malloc(count);
}
int main() {
std::string str;
std::cout << std::endl;
std::string str1 = "Test string";
std::cout << str1.size() << " " << str1[5] << std::endl << std::endl;
std::string str2 = "Test string Test string Test string";
std::cout << str2.size() << " " << str2[5] << std::endl << std::endl;
std::u32string u32_str = U"This is UTF-32";
std::cout << u32_str.size() << " " << u32_str[5] << std::endl << std::endl;
return 0;
}
Then the output of this code is...
8 bytes allocation
8 bytes allocation
11 s
8 bytes allocation
48 bytes allocation
35 s
8 bytes allocation
64 bytes allocation
14 105
I override operator new. I make new operator prints something as you see.
str2is long string literal, so I understand memory space is needed for"Test string Test string Test string". Also I understand memory space is not needed for short stringstr1. Why do we need eight bytes? Where did the eight bytes come from?The utf32 encoding method processes all characters by 4 bytes. Why is the
size()result value ofstr314 bytes instead of 14 * 4 = 56 bytes?