vedaanta
vedaanta

Reputation: 31

Reference to a queue that resides on function stack

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.

Upvotes: 0

Views: 211

Answers (1)

alter_igel
alter_igel

Reputation: 7212

Your understanding that a reference can only be assigned once is correct. References are aliases to objects in the sense that they are not objects themselves, but always refer to another object. By design, their syntactic usage is to act as a drop-in replacement for concrete objects in most cases. Pointers on the other hand can be made to point to a different object or to nullptr.

The result of q = q2 is that q2's contents are assigned to the queue referred to by q. This is indeed a deep copy, and the function-local q2 is not referred to thereafter, and there is no dangling reference.

Documentation for queue's operator= can be found here.

Upvotes: 1

Related Questions