I don’t understand why the following does not work:
queue<int*> q;
int counter = 1;
for (int i = 0; i < 3; i++) {
int a[1] = {counter};
q.push(a);
counter++;
}
while (!q.empty()) {
int *top = q.front();
q.pop();
cout << top[0] << endl;
}
It should print out: 1 2 3, but instead 3 3 3 is printed out. This is because the pointers in the queue are all the same after each run through the loop. Why does that happen?
You are storing pointers to local variables and using those pointers after the local variables they point to have gone out of scope.
In other words: you are invoking Undefined Behavior.
Result: It should not print out “1 2 3”. It doesn’t have to do anything and is allowed to do whatever it likes. “3 3 3” seems reasonable to me, as it is also allowed to crash.