Here is some C++ code that use a queue.
#include <iostream>
#include <queue>
using namespace std;
void print(queue<int>& q){
int n = q.size();
for (int i = 0; i < n; ++i){
int front = q.front();
cout<<front<<" ";
q.pop();
q.push(front);
}
cout<<endl;
}
template <typename T>
void foo(queue<T>& q){
queue<T> q2;
for(int i=4;i<7;i++)
q2.push(i);
q = q2;
}
int main(){
queue<int>q;
for(int i=1;i<4;i++)
q.push(i);
print(q);
foo(q);
print(q);
}
A queue q is declared in the main function and is passed as a reference in the function foo. But it is reassigned to another queue q2 that occupies memory inside the function stack space.
From what I understand, after the function foo terminates, the reference variable should point to an invalid memory address as the queue q2 would have been destroyed.
Could anyone help me with these two questions?
1. Why does q hold the correct elements of q2, even though the queue q2 has been destroyed after function call terminates.
2. A reference variable is supposed to a initialized only once. But it seems we can assign it different values as many times as we like. Why is this allowed?
I have been thinking of this being an implication of deep copy. But I have not been able to find the internal implementation of the copy assignment operator that queue STL has. I would be great if someone could help me with a link to that.
qis assigned fromq2; that is the contents ofq2are placed intoq. Now go back to this part, and work the rest of it out, and everything will make sense.