简体   繁体   中英

Second argument to std::vector

Looking at vector , I realized that I have never used the second argument when creating vectors.

std::vector<int> myInts; // this is what I usually do
std::vector<int, ???> myOtherInts; // but is there a second argument there?

Looking at the link above it says that it is for:

Allocator object to be used instead of constructing a new one.

or, as for this one :

Allocator: Type of the allocator object used to define the storage allocation model. By default, the allocator class template for type T is used, which defines the simplest memory allocation model and is value-independent.

I guess it has to do with something with memory management. However, I am not sure how to use that.

Any pointers regarding this?

The default allocator, std::allocator<> , will handle all allocations made by std::vector<> (and others). It will make new allocations from the heap each time a new allocation is needed.

By providing a custom allocator, you can for instance allocate a big chunk of memory up front and then slice it up and hand out smaller pieces when separate allocations are needed. This will increase the allocation speed dramatically, which is good for example in games, at the cost of increased complexity as compared to the default allocator.

Some std type implementations have internal stack-based storage for small amounts of data. For instance, std::basic_string<> might use what is called a small string optimization , where only strings longer than some fixed length, say 16 characters (just an example!), gets an allocation from the allocator, otherwise an internal array is used.

Custom allocators are rarely used in general case. Some examples of where they can be useful:

  • Optimization for a specific pattern of allocations. For example, a concurrent program can pre-allocate a large chunk of memory via standard means at the beginning of task execution and then shave off pieces off it without blocking on the global heap mutex. When task is completed, entire memory block can be disposed of. To use this technique with STL containers, a custom allocator can be employed.

  • Embedded software, where a device has several ranges of memory with different properties (cached/noncached, fast/slow, volatile/persistent etc). A custom allocator can be used to place objects stored in an STL container in a specific memory region.

Maybe this will help: http://www.codeguru.com/cpp/cpp/cpp_mfc/stl/article.php/c4079

You may try google for: stl allocator .

Allocators (STL) help you to manage memory for your objects in vector class. you may use the custom allocator for different memory model( etc).

嗨,您可以找到自定义分配器的示例http://www.codeproject.com/KB/cpp/allocator.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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