what's the distinguish from vector<string> and vector<string, allocator>?

Answered what's the distinguish from vector<string> and vector<string, allocator>?

  • Saturday, August 18, 2012 3:48 AM
     
     

    Hello all,

    I'm self-studying C++ and my question is like the title.

    So,

    1. what is the difference?

    2. how do we determine which format we really need in different situation?

    Thanks,

    Cup,

All Replies

  • Saturday, August 18, 2012 3:58 AM
     
     Answered

    Whenever a vector needs additional space from a push_back call, it needs to call a function to allocate additional space. By default it uses an "allocator object" do carry out this job. It is possible to overwrite this with your own allocator if you need precise control over memory management.

    This is a rarely used feature, and I'd advise you that you can defer this aspect of C++ until you are a more experienced C++ programmer. In fact, I have never written an allocator for a commercial program in the past 15 years and I believe this feature is seldom required.

  • Saturday, August 18, 2012 5:17 AM
     
     
    I have heard the use of a custom allocator is common practice in game programming where large amounts of objects are pushed to collections.

    Jose R. MCP
    Code Samples

  • Saturday, August 18, 2012 11:17 AM
     
     Answered

    On 18/08/2012 05:48, CupOverTheTable wrote:


    1. what is the difference?

    2. how do we determine which format we really need in different situation?

    vector<string> uses the default allocator, which is based on C++'s "new" (which is based on C's malloc(), which calls Win32's HeapAlloc()).

    There are cases in which (for performance reasons) you want to customize the allocation process, for example, you may want to implement a pool allocator like this:

    http://blogs.msdn.com/b/oldnewthing/archive/2005/05/19/420038.aspx

    In these cases you can specify a custom allocator for STL classes like vector or string.

    Boost does have some custom allocators for specific needs; you can plug these allocators into STL containers.

    There is a blog post on VCBlog in which Mr.STL shows the implementation of a custom allocator (but I'm not sure it works in VC10...):

    http://blogs.msdn.com/b/vcblog/archive/2008/08/28/the-mallocator.aspx

    Giovanni