SSO(Short string optimization) & utf-32 encoding question

Viewed 53

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.

  1. str2 is 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 string str1. Why do we need eight bytes? Where did the eight bytes come from?

  2. The utf32 encoding method processes all characters by 4 bytes. Why is the size() result value of str3 14 bytes instead of 14 * 4 = 56 bytes?

1 Answers

That's another instance of the Microsoft compiler being wrong, in this case subtly so. Both gcc and clang implement short string optimisation correctly.

11 s

36 bytes allocation
35 s

60 bytes allocation
14 105
Related