bhikkhu's blog

By bhikkhu, 7 years ago, In English
#include <vector>
#include <utility>
#include <cassert>
int main() {
    std::vector<int> vec;
    vec.push_back(0);
    int & r = vec[0];
    if (r == 0) {
        r = 1;
        vec.push_back(0);
    }
    assert(r > 0);
    return 0;
}

Find out why this code is dangerous :D

I became a victim of this problem while solving a problem using logic similar to the code shown.

  • Vote: I like it
  • +33
  • Vote: I do not like it

»
7 years ago, # |
  Vote: I like it +24 Vote: I do not like it

By inserting another element, the vector will double its capacity and thus the memory address may change. Is it correct?

»
7 years ago, # |
  Vote: I like it +24 Vote: I do not like it

It's dangerous because in the second push_back, the vector reallocates new array of double length, and deletes the old one. (If you don't know how vector works, see this.)

Hence, r becomes pointing to an invalid memory position, so its value will be just garbage. One way to make sure of this, is to add the following line before doing any push_backs.

vec.reserve(2);