fredoverflow
fredoverflow

Reputation: 263220

Does reserving capacity incur two allocations or just one?

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?

Upvotes: 4

Views: 145

Answers (3)

tzaman
tzaman

Reputation: 47820

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,

Upvotes: 2

dash-tom-bang
dash-tom-bang

Reputation: 17853

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.

Upvotes: 0

Billy ONeal
Billy ONeal

Reputation: 106589

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.

Upvotes: 7

Related Questions