Does the reserve potential have two distributions or only one?

std::vector<T> vec; // line #1 vec.reserve(100); // line #2 

I am wondering if line # 1 starts a small allocation (say, 10 Ts memory) or if the first allocation happens on line # 2. Does the standard say that?

+4
source share
3 answers

Implementation defined. The default constructor for vector should not allocate anything, but this is acceptable for implementation.

+7
source

The standard does not say, but you can see for yourself that this is in your system:

 vector<int> v; cout << v.capacity() << endl; v.reserve(100); cout << v.capacity() << endl; 

This gives me 0 and 100 on VS2008 - i.e. the original vector has nothing selected.

EDIT: erroneous advice removed.
EDIT2: A little experiment because I was curious ...

 vector<int> w; for (int i=0; i<100000; i++) { if (i == w.capacity()) cout << i << ", "; w.push_back(i); } 

Conclusion:

 0, 1, 2, 3, 4, 6, 9, 13, 19, 28, 42, 63, 94, 141, 211, 316, 474, 711, 1066, 1599, 2398, 3597, 5395, 8092, 12138, 18207, 27310, 40965, 61447, 92170, 
+2
source

The first, as a rule, does not initiate allocation, in addition to space for the vector container on the stack (which will include information about how much space has been allocated and how much is used, which is zero). But heap distribution does not happen until you stock up .... usually.

0
source

Source: https://habr.com/ru/post/1308514/


All Articles