C ++ maximum length std :: string dictated by stack size or heap size?

as asked in the question.
std :: string myVar; Is the maximum character that it can hold determined by the stack or heap?

thanks

+6
source share
2 answers

By default, the memory allocated for std::string is allocated dynamically.

Note that std::string has a max_size() function that returns the maximum number of characters supported by the implementation. However, the usefulness of this question is doubtful, since it is a maximum implementation and does not take into account other resources, such as memory. Your real limit is much lower. (Try allocating 4 GB of continuous memory or consider memory exhaustion elsewhere.)

+8
source

The object A std::string will be distributed in the same way as int or any other type should be: on the stack if it is a local variable, or it can be static , or on the heap if new std::string used or new X , where X contains string , etc.

But, that a std::string object can contain at least a pointer to the additional memory provided by the allocator with which the basic_string <- instance was created for std::string typedef , which means allocated memory. Either directly in the source memory of an std::string object, or in a heap of a point that you can find:

  • member of row size
  • maybe some kind of link or link counter,
  • text data stored in a string (if any)

In some std::string implementations there is an optimization of β€œshort lines”, where they pack lines of only a few characters directly into the line object itself (for memory efficiency, often using some kind of union with fields that are used for other purposes when the lines are longer) . But for other string implementations and even for optimizers with short strings when working with strings that are too long for the std :: string object, they will have to follow pointers / links to text data that are stored in memory provided by the allocator (heap).

+2
source

Source: https://habr.com/ru/post/885474/


All Articles