hi guys so I decided to get the size of a string because I may need to use the locations for file pointers anyway I see that it is on my machine anyway (windows 64 bit MinGW compiler eclipse cdt) 32 bytes,but I read somewhere that some compilers optimise strings so if a string is small it saves it in a 32 byte piece of memory on the stack and if it grows larger than that it will dynamically allocate memory anyway I tested this and I don't think that is true,
because I put in a ridiculously long string and I'm talking massive string maybe a thousand characters long and when I checked the size of the string with the sizeof function/operator it still gave me 32 bytes,
how is this possible considering each char is a byte long in it's own right,no way can this be possible,
Yes, it may keep track of pointers, its own size, and other possible internal, implementation-side optimizations.
If you were to run
1 2 3 4 5 6 7 8
// Example program
#include <iostream>
#include <string>
int main()
{
std::cout << sizeof(std::string) << std::endl;
}
in http://cpp.sh , you'll see that compiler says sizeof(string) is 8.
adam2016 wrote:
so I decided to get the size of a string because I may need to use the locations for file pointers
I'm not sure what exactly this means, but if you're planning on writing the std::string to a file in a manner such as f.write((char*)my_str, sizeof(my_str));, note that this won't contain the string characters itself (because that's dynamic memory), and won't be portable even across different version of the same compiler. So avoid this. Write the characters themselves to file.
But my advice is to not be worried about the size of std::string unless you're making millions of strings, and you have, through proper methods, determined that it's a bottleneck in your program. http://wiki.c2.com/?PrematureOptimization