Initial capacity of vector in C++

后端 未结 6 1598
独厮守ぢ
独厮守ぢ 2020-11-28 12:47

What is the capacity() of an std::vector which is created using the default constuctor? I know that the size() is zero. Can we state t

6条回答
  •  眼角桃花
    2020-11-28 13:00

    This is an old question, and all answers here have rightly explained the standard's point of view and the way you can get an initial capacity in a portable manner by using std::vector::reserve;

    However, I'll explain why it doesn't make sense for any STL implementation to allocate memory upon construction of an std::vector object;

    1. std::vector of incomplete types;

      Prior to C++17, it was undefined behavior to construct a std::vector if the definition of T is still unknown at point of instantiation. However, that constraint was relaxed in C++17.

      In order to efficiently allocate memory for an object, you need to know its size. From C++17 and beyond, your clients may have cases where your std::vector class does not know the size of T. Does it makes sense to have memory allocation characteristics dependent on type completeness?

    2. Unwanted Memory allocations

      There are many, many, many times you'll need model a graph in software. (A tree is a graph); You are most likely going to model it like:

      class Node {
          ....
          std::vector children; //or std::vector< *some pointer type* > children;
          ....
       };
      

      Now think for a moment and imagine if you had lots of terminal nodes. You would be very pissed if your STL implementation allocates extra memory simply in anticipation of having objects in children.

      This is just one example, feel free to think of more...

提交回复
热议问题