sturmer
sturmer

Reputation: 350

Calling vector::reserve() on a vector reference

I have put together a theory that explains a phenomenon, but I'd like someone more knowledgeable to bear me up.

In the client code, I have:

vector<bool> candidates;
fillCandidates(candidates);

In the callee, I have:

void fillCandidates(vector<bool>& candidates)
{
    // reserve space for two elements
    candidates.reserve(2);
    candidates[0] = true;
    candidates[1] = false;
    // here, candidates.size() == 0
}

When I check the size of candidates after the return of the function, it is 0! What's happening? I'm using gcc 4.6.3 called in a CMake script on a Ubuntu 12.04 64-bit (but I think all of this is actually irrelevant).

Note: I'm providing my interpretation as an answer.

Edit: The accepted answer and the comments beat me on timing, so my interpretation wouldn't add anything.

Upvotes: 1

Views: 227

Answers (1)

Salgar
Salgar

Reputation: 7795

You should be calling resize, not reserve.

See the differences here: Choice between vector::resize() and vector::reserve()

Edit to answer comments below:

The short answer is yes, calling operator[] on a vector that is only reserved is an error, and anything could happen.

The long answer is read this article http://www.gotw.ca/gotw/074.htm

v.reserve( 2 ); v[0] = 1; v[1] = 2; Both of the above lines are flat-out errors, but they might be hard-to-find flat-out errors because they'll likely "work" after a fashion on your implementation of the standard library.

I suggest reading the whole thing. In your case I would use push_back instead of resizing manually. But I would benchmark performance if you are really concerned.

Upvotes: 4

Related Questions