简体   繁体   English

C ++ STL问题:分配器

[英]C++ STL question: allocators

I have a (potentially dumb) question about the C++ STL. 我有一个关于C ++ STL的(可能是愚蠢的)问题。 When I make a container (vector, set, map, etc), is it allocated on the stack or on the heap? 当我创建一个容器(向量,集合,映射等)时,它是在堆栈上还是在堆上分配的? If I make a set and put 5 million strings, will I have to worry about a stack overflow? 如果我制作一组并放置500万个字符串,我是否需要担心堆栈溢出?

默认情况下,STL类从堆中分配其内部缓冲区,尽管这些类还允许自定义分配器允许用户指定要从中分配的备用位置 - 例如共享内存池。

The default allocator for STL containers uses operator new and delete, so it's whatever those route to for the type being contained. STL容器的默认分配器使用operator new和delete,因此它是包含所包含类型的路由。 (In general, it comes from the heap unless you do something to override that.) (一般来说,它来自堆,除非你做一些事情来覆盖它。)

You will not get a stack overflow from allocating 5 million strings. 分配500万个字符串不会导致堆栈溢出。 Even if you made a stack based allocator, it would probably overflow before you even inserted one string. 即使您创建了基于堆栈的分配器,它甚至可能会在您插入一个字符串之前溢出。

The container itself is allocated where you decide (it can be the stack, the heap, an object's member, etc) but the memory it uses is, by default, as others described, taken on the Free Store (managed through new and delete) which is not the same as the heap (managed through malloc/free). 容器本身是在您决定的地方分配的(它可以是堆栈,堆,对象的成员等),但默认情况下,它使用的内存与其他描述的一样,在Free Store上进行(通过new和delete管理)这与堆不同(通过malloc / free管理)。

Don't mix the two! 不要把两者混在一起!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM