How is C++ std::vector implemented?

后端 未结 9 1352
不思量自难忘°
不思量自难忘° 2020-11-28 06:49

I have been using std::vector a lot, and recently I asked myself this question: \"How is std::vector implemented?\"

I had two alternatives:

9条回答
  •  忘掉有多难
    2020-11-28 07:36

    A pedagogic (and thus simplified) version of a container called "Vec" is discussed in Chapter 11 of the wonderful (introductory) book "Accelerated C++". What they describe is a stripped-down version of std::vector, but I think it is still worth noting that:

    1) they implement their template class in terms of an array,

    2) they discuss push_back in terms of the trick (mentioned above) of allocating more storage than is needed, and coming back for more when they run out, and

    3) they use allocator> for memory management. The new operator is not flexible enough in this context, since it both allocates and initializes memory.

    I repeat, though, that this doesn't mean that actual implementations out there are this simple. But since "Accelerated C++" is quite widespread, those interested can find in the relevant chapter one way vector-like objects can be created, copied, assigned, and destroyed.

    EDIT: On a related note, I just found the following blog post by Herb Sutter in which he comments on an earlier blog post by Andrew Koenig, regarding whether or not one should be worried about vector elements being contiguous in memory: Cringe not: Vectors are guaranteed to be contiguous.

提交回复
热议问题