views:

78

answers:

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

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

+7  A: 

It's implementation defined. The default-constructor for vector does not need to allocate anything, but it's permissible for an implementation to do so.

Billy ONeal
A: 

The first one doesn't typically trigger an allocation, besides space for the vector container on the stack (which will include info regarding how much space has been allocated and how much is used, which'll both be zero). But the heap allocation doesn't happens until you reserve. ...typically.

dash-tom-bang
Typically, yes, but the standard says nothing of it.
Billy ONeal
+2  A: 

The standard doesn't say, but you can find out for yourself what it is on 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 initial vector has nothing allocated.

EDIT: removed erroneous advice.
EDIT2: 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);
}

Output:

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,
tzaman
+1 for the first half of the answer, -1 for the second half. `w(100)` is different than `w(); w.reserve(100)`, because using the constructor default constructs 100 elements. (i.e. `size` is also 100 after construction in your second example)
Billy ONeal
Oh, darn, you're right, of course. I'll remove that bit.
tzaman
@tzaman: `vector` grows in size exponentially in order to meet the requirement that `push_back` can have amortized constant time complexity. Just an FYI, since you posted the experiment. :-)
James McNellis
+1 now that the answer is fixed.
Billy ONeal
@James, I know about the proportional growth requirement :) I was more intrigued by the initial behavior (the first *four* inserts all allocate just one extra element..)
tzaman