1

Simple question:

vector<int> vi;
vi.reserve(1984);
vi[84] = 1900;

Is this legal? Note we are talking int here not some Widget whose dtor might cause mayhem because it thinks element at position 84 is being destroyed, while at pos 84 there is just random(or maybe zero-d) memory.

NoSenseEtAl
  • 28,205
  • 28
  • 128
  • 277
  • You should probably be using `vi.resize()` in this case, rather than `vi.reserve()` – benjymous Oct 31 '13 at 16:31
  • Intuitively this is undefined behavior but I'm having a hard time tracking down exactly how this is spelled out in the standard. – Mark B Oct 31 '13 at 17:22

1 Answers1

2

No, it is not legal. Access to elements is only allowed for 0 to size()-1 (when the vector is not empty). If it's empty, no access to the non-existing elements is allowed.

For int this doesn't make much sense but for a UDT T, it's the difference between a chunk of memory that is able to hold a T (that's what reserve() provides) and an actual instance of T which is only there when it is in the valid range of 0 to size()-1.

Daniel Frey
  • 55,810
  • 13
  • 122
  • 180
  • ok, but thinking about implementation of vector I see no reason why this would not work, can you cite ISO for [0, size()-1) requirement... anyway this is mostly theoretical since resize should not be more expensive than reserve :) – NoSenseEtAl Oct 31 '13 at 16:35
  • @NoSenseEtAl If you accept that `v[n]` is only valid if `v.at(n)` is, then 23.2.3/17 should answer it. – Daniel Frey Oct 31 '13 at 16:41
  • @NoSenseEtAl: Actually `resize` is more expensive because it needs to value initialize the whole part (for `int`, value initialization means initializing to zero. – Siyuan Ren Oct 31 '13 at 17:23