vector::reserve,

Q

quat

Hi,

Is it not legal to access an element that has been reserved?

For example:

vector<int> x;
x.reserve(10);

x[0] = 1;

This is throwing an exception with VS 2005, but worked fine for VS 2002.

From what I understand, reserve allocated memory but does not adjust the
internal "size" member. So technically, I should be able to access the
elements?
 
R

Rolf Magnus

quat said:
Hi,

Is it not legal to access an element that has been reserved?

Yes, it is not.
For example:

vector<int> x;
x.reserve(10);

x[0] = 1;

This is throwing an exception with VS 2005, but worked fine for VS 2002.

From what I understand, reserve allocated memory but does not adjust the
internal "size" member.

Reserve allocates memory, but doesn't create any objects. The above vector
contains 0 objects of type int, but you can add (e.g. with push_back) at
least 10 without a reallocation happening. You can't access any objects
yet, because there are still none in the vector. Whatever "internal"
members a vector might or might not have is of no relevance for that.
That's an implementation detail you aren't supposed to care about.
So technically, I should be able to access the elements?

No, because there are no elements yet. If you want a vector with 10
elemenents, try using resize() instead of reserve().
 
Q

quat

No, because there are no elements yet. If you want a vector with 10
elemenents, try using resize() instead of reserve().

I can accept this. However, I don't get how an allocation can occur without
creating objects. Presumably, reserve does something like this:

data = new type[n]; // where n = amount to reserve.

Thus data[j] should be accessible for 0 <= j < n.
 
R

Rolf Magnus

quat said:
No, because there are no elements yet. If you want a vector with 10
elemenents, try using resize() instead of reserve().

I can accept this. However, I don't get how an allocation can occur
without
creating objects. Presumably, reserve does something like this:

data = new type[n]; // where n = amount to reserve.

There are ways of allocating raw memory without creating objects (using
global operator new), and there are ways of turning that raw memory (using
placement new).
Thus data[j] should be accessible for 0 <= j < n.

It might be, but there is no guarantee, unless you actually resize the
vector.
 
Q

quat

There are ways of allocating raw memory without creating objects (using
global operator new), and there are ways of turning that raw memory (using
placement new).

Okay I didn't know this. Thanks.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,776
Messages
2,569,602
Members
45,182
Latest member
BettinaPol

Latest Threads

Top