#include <iostream> #include <string> static uint32_t s_AllocCount = 0; // Overload of new operator. void* operator new(size_t size) { s_AllocCount++; std::cout << "Allocating " << size << " bytes\n"; return malloc(size); } void PrintName(const std::string& name) { std::cout << name << " - " << name.length() << " characters." << std::endl; } int main() { std::string name = "123456789012345"; PrintName(name); std::cout << s_AllocCount << " allocations" << std::endl; std::cin.get(); } The above code is a slightly modified version of that in How to make your STRINGS FASTER in C++!.
I am puzzled about the various outputs from this program in Visual Studio 2019 compiled in x86 debug.
When std::string name = "123456789012345"; the following results:
I understand that 8 bytes are being allocated for the pointer address. What I don't understand is that there are 15 bytes in this string. Does not the pointer address point to an 8 byte block of memory, i.e., one which can hold 8 characters?
When std::string name = "1234567890123456";, i.e., lengthened by 1 character to 16, the result is:
Now, an additional 32 bytes of memory have been allocated, clearly enough to hold 16 characters.
Do I understand correctly:
That in the first case only 8 bytes of heap memory are being allocated for storing the string's pointer address and that the 15 characters of the string are stored on the stack?
In the second case that 40 bytes of heap memory are being allocated and that both the string's pointer address and the string characters are all stored on the heap?
This question was suggested by the author of the referenced video regarding the use of std::string in OpenGL. Specifically, he suggested that the willy-nilly use std::string in OpenGL can substantially slow dynamic scene changes. Now I am trying to better understand just how much memory is being allocated and where so that at least I know when it might be slowing a program.
Since I slightly modified this program, perhaps the code is not doing what I think it is doing, i.e., that I have made a programming mistake. If that is the case, I would appreciate the error(s) being identified.


std::string, and for string lengths lower then 15 bytesstd::stringis using internal memory instead of allocating. Does emptyint main () {}also allocate 8 bytes? Doesmain() { std::cout << ""; }also allocate 8 bytes?std::stringallows small string optimization (which generally amounts to using two of the three pointer-sized members as character storage instead of their normal functionality, i.e. distinct behavior for 16 vs 17 bytes), the string should not be allocating anything in the first case. I assume youroperator newis being called for something else than the string constructor.std::string_viewfor getting a view into a string instead of needlessly creating them.