> The C++ string library cannot bind the string to the stack frame since it doesn't know how long it's going to live.
Huh? If course it could, unless I'm not understanding you correctly.
A class like:
class smallstr {
char stack_str[128];
char* heap_ptr;
}
can easily (with enough logic in the public methods) store small strings in `stack_str` and once it grows larger, allocate some space on the heap, make `heap_ptr` point to it, and copy it over.
"since it doesn't know how long it's going to live" doesn't make any sense to me. A caller would just say:
{
smallstr s("foo");
// do stuff
} // stack_str[] is wiped clean with the stack, and a destructor would be implemented to `delete` heap_ptr if it was used.
Well, you have to take the context of our discussion in consideration, I meant that you couldn't dynamically elect to allocate your buffer on the stack instead of the heap at runtime in the constructor. Your solution just allocates a 128B buffer on the stack for all strings which may or may not end up being used.
That makes your string object 128B larger in all situations. Since we were talking about std::string, I'm pretty sure many people wouldn't be happy if sizeof(std::string) suddenly took 128B (g++'s sizeof(std::string) is 8B on my system).
What I had in mind was stuff like alloca and other local scope allocation techniques that would get tied to the constructor stack frame not the caller's.
g++'s sizeof(std::string) is only 8 bytes because it's a single pointer such that the struct can be reinterpret_casted to a const char * and you get the same thing that c_str() gives you. It's reference-counted (across threads!), copy-on-write. I don't think people would mind a 24-byte std::string (on 64-bit systems), which would consist of a pointer, size, and capacity, and which would allow 22-byte strings to be stored inline.
On Windows, sizeof(std::string) is 24 or 32 depending on 32- or 64-bit. sizeof(vector<char>) is 12 and 24, respectively, of course. I believe the extra size of the std::string is for storing strings inline. I'd guess their implementation looks like struct { char *ptr; size_t size; union { size_t capacity; char buf[16]; } u; };, which sacrifices some size in favor of keeping the code paths simple.
Huh? If course it could, unless I'm not understanding you correctly.
A class like:
can easily (with enough logic in the public methods) store small strings in `stack_str` and once it grows larger, allocate some space on the heap, make `heap_ptr` point to it, and copy it over."since it doesn't know how long it's going to live" doesn't make any sense to me. A caller would just say:
I'm not sure what you're even driving at.