Originally Posted by
_Mike
Hahaha oh the irony
Where do all these "experts" come from?
FYI, look up how std::string works. (Yes I know this is c# but either way this guy couldn't have been more wrong even if it was c++)
Well that was embarassing haha, that should teach me to guesswork at 3am.
Nevermind my post obviously, too much C these years and too many years since i touched c++ let alone c#
Of course, barring any optimization, name is stack allocated, but that's only the string object container, the memory space for the content itself is elsewhere (likely allocated on the heap at object creation), and, most importantly, the return would make a copy of the object for the caller. With optimizations the string might directly be allocated at an address given by the caller.
As penance for my crimes, I fired up visual studio to check the implementation in more detail. Microsoft's implementation of std::string is a 28 bytes structure (on a 32 bit architecture) or 32 bytes in debug mode, with a pointer to the string at offset 4 and the length at offset 20. Interestingly enough, for the same very simple example (std::string constructed from a C string), the libstd++ implementation is only 4 bytes big (32 bits architecture again) and simply contains a pointer to a copy of the string. This can't be all of it.
Digging deeper, the MS standard lib implementation is big because it also has a short string buffer inside the structure, so very short strings aren't even dynamically allocated. If the string is 16 bytes or lower (including ending null), it's directly included in the container. So in short, MS implementation of std::string is (again, this is all on a 32 bits system) :
Code:
+ 0 ( 4 bytes) : allocator base class ?
+ 4 (16 bytes) : either pointer to the allocated string, or the string itself if it fits inside 16 bytes
+20 ( 4 bytes) : length of the string (not including ending null)
+24 ( 4 bytes) : seems to be allocated memory for the string (not including ending null)
The GCC library does it differently. The std::string container is just one pointer, pointing to the memory allocated for the string directly. The rationale behind it being that it's easier for debugging purposes if the string object directly points to the string itself (see libstdc++: basic_string.h Source File for the documentation). The rest of the structure is located before the string in memory :
Code:
(4 bytes) length (not including ending null)
(4 bytes) allocated memory for the string (not including this 3 word header nor ending null)
(4 bytes) reference count (-1:leaked, 0:one reference, 1+:multiple references)
std::string : (4 bytes) pointer -----> array of char
PS : god, i hate^H^H^H^Hdislike c++.