How does std::vector implement the management of the changing number of elements: Does it use realloc() function, or does it use a linked list?
Thanks.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It uses the allocator that was given to it as the second template parameter. Like this then. Say it is in push_back, let
tbe the object to be pushed:Something like that. The allocator will care about allocating memory. It keeps the steps of allocating memory and constructing object into that memory apart, so it can preallocate memory, but not yet call constructors. During reallocate, the vector has to take care about exceptions being thrown by copy constructors, which complicates the matter somewhat. The above is just some pseudo code snippet – not real code and probably contains many bugs. If the size gets above the capacity, it asks the allocator to allocate a new greater block of memory, if not then it just constructs at the previously allocated space.
The exact semantics of this depend on the allocator. If it is the standard allocator, construct will do
And the allocate
allocatewill just get memory from::operator new.destroywould call the destructorAll that is abstracted behind the allocator and the vector just uses it. A stack or pooling allocator could work completely different. Some key points about
vectorthat are importantreserve(N), you can have up to N items inserted into your vector without risking a reallocation. Until then, that is as long assize() <= capacity(), references and iterators to elements of it remain valid.