开发者

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?


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.


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,


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜