#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.
By inserting another element, the vector will double its capacity and thus the memory address may change. Is it correct?
You are right
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.