std::vector: Memory allocation in copy constructor for empty vector

Paolo Carlini pcarlini@suse.de
Wed Sep 5 10:13:00 GMT 2007


Hi,

interesting issue...

>in the default constructor of the std::vector a zero sized vector is
>created. If this vector is copied
>with the copy constructor a memory block of size zero is allocated,
>resulting in a real memory allocation.
>
>This behavior has changed as the std::allocator changed from a separate
>implementation to the
>__glibcxx_base_allocator somewhere around 2004 (we recently changed from
>gcc 3.3.2 to 4.1.0).
>
>Because we use something like:
>vector <vector <int> > v;
>v.resize (1000000);
>
>That gave use a huge bunch of memory allocations :-(
>  
>
Yes, previously, __simple_alloc::allocate avoided calling 
_Alloc::allocate when __n == 0. Therefore this intermediate layer took 
care of avoiding pointless allocations.

>So here are my questions:
>1) Is there an easy standard way to change the default allocator? Not per
>instance - this would be
>   way to much to change :-(
>2) Is there a chance that the copy constructor of the vector (or the
>allocator) will be changed to
>   the former behavior? (I guess the standard don't say anything about
>which of both is correct)
>  
>
I think we should do 2), seems doable. I'm looking into it.

You could certainly do 1) and choose one among the various available 
allocators at configure time 
(http://gcc.gnu.org/onlinedocs/libstdc++/configopts.html), but even in 
the best cases the library would still waste the time of the 
Alloc::allocate call, even when the latter returns immediately 
(__pool_alloc for instance).

Paolo.



More information about the Libstdc++ mailing list