最大 std::string 长度是由堆栈大小还是堆大小决定的?
std::string myVar;
myVar
可以容纳的最大字符是由堆栈还是堆决定的?
std::string myVar;
Is the maximum character myVar
can hold is dictated by stack or heap?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
默认情况下,为
std::string
分配的内存是动态分配的。请注意,
std::string
有一个max_size()
函数,返回实现支持的最大字符数。不过,它的用处值得怀疑,因为它是实现最大值,并且没有考虑其他资源,例如内存。你的真正限制要低得多。 (尝试分配 4GB 连续内存,或考虑其他地方的内存耗尽。)By default, the memory allocated for
std::string
is allocated dynamically.Note that
std::string
has amax_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.)std::string
对象的分配方式与int
或任何其他类型必须相同:如果它是局部变量,则在堆栈上,或者它可能是>static
,或者如果使用new std::string
或new X
,则在堆上,其中X
包含string
等。但是,
std::string
对象可能至少包含一个指向由 basic_string<> 分配器提供的附加内存的指针。被实例化 - 对于std::string
typedef
来说,这意味着堆分配的内存。无论是直接在原始 std::string 对象内存中还是在指向堆中,您都可以找到:一些
std::string
实现具有“短字符串”优化,它们将只有几个字符的字符串直接打包到字符串对象本身中(为了提高内存效率,通常使用某种与当字符串较长时用于其他目的的字段)。但是,对于其他字符串实现,甚至对于那些在处理太长而无法直接放入 std::string 对象的字符串时进行短字符串优化的实现,它们也必须遵循对存储的文本数据的指针/引用在分配器提供的(堆)内存中。A
std::string
object will be allocated the same way anint
or any other type must be: on the stack if it's a local variable, or it might bestatic
, or on the heap ifnew std::string
is used ornew X
whereX
contains thestring
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 thestd::string
typedef
that means heap-allocated memory. Either directly in the originalstd::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.