r18ul
r18ul

Reputation: 1064

Why does the value returned from front() exist even after pop() from std::queue?

I'm collecting the value returned from queue::front() into a local variable. As per documentation, queue::front() returns the reference. So if I pop it off from the queue, how can the collected value still exist?

int main()
{
    std::string val;
    {
        std::queue<std::string> q;
        q.push("one");
        q.push("two");
        q.push("three");
        val = q.front();
        q.pop();
        q.pop();
        q.pop();
        std::cout << "is queue empty: " << boolalpha << q.empty() << '\n';
    }

    std::cout << "val: " << val << '\n';
}

The output is:

is queue empty: true
val: one

Why does val still has "one" after pop()'ing

Upvotes: 1

Views: 737

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409176

Because val is not a reference. Not to the front of the queue or anywhere else.

When you do

val = q.front();

you copy what's currently at the front of the queue into val.

What you do later with the queue will not affect this copy.

If you want a reference then you need to make val a reference.

And remember that by making val a reference, it will only reference one single element in the queue. Once you pop the front once, that reference becomes invalid. Adding new elements will not change your reference, it will still reference the same element in the queue, it will not reference the new front. And you can not rebind a reference once bound.

All in all, using references to elements in a queue is in most use-cases pretty useless.

Upvotes: 1

Related Questions