as asked in the question.
std::string myVar; the maximum character it can hold is dictated by stack or heap?
Thank you
By default, the memory allocated for std::string
is allocated dynamically.
Note that std::string
has a max_size()
function returning the maximum number of character supported by the implementation. The usefulness of this is questionable, though, as it's a implementation maximum, and doesn't take into consideration other resources, like memory. Your real limit is much lower. (Try allocating 4GB of contiguous memory, or take into account memory exhaustion elsewhere.)
A std::string
object will be allocated the same way an int
or any other type must be: on the stack if it's a local variable, or it might be static
, or on the heap if new std::string
is used or new X
where X
contains the string
etc..
But, that std::string
object may contain at least a pointer to additional memory provided by the allocator with which basic_string<> was instantiated - for the std::string
typedef
that means heap-allocated memory. Either directly in the original std::string
object memory or in pointed-to heap you can expect to find:
Some std::string
implementations have "short string" optimisations where they pack strings of only a few characters directly into the string object itself (for memory efficiency, often using some kind of union with fields that are used for other purposes when the strings are longer). But, for other string implementations, and even for those with short-string optimisations when dealing with strings that are too long to fit directly in the std::string object, they will have to follow pointers/references to the textual data which is stored in the allocator-provided (heap) memory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With