Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference list element then popping it, is it undefined behaviour?

I have this piece of code and I wonder if it is valid or can cause undefined behaviour:

#include <list>
#include <utility>

void myFunction(std::list<std::pair<int, int>> foo)
{
    while (foo.size())
    {
        std::pair<int, int> const &bar = foo.front();

        //work with bar

        foo.pop_front();
    }
}

I am using a reference to avoid duplicating the already existing pair.

On one side, I think this could be an undefined behaviour because I am removing a referenced element but, on the other side, I am not accessing the reference after removing it.

Is it valid?

like image 981
f222 Avatar asked Nov 18 '25 19:11

f222


1 Answers

So long as you don't attempt to use the bar reference after the foo.pop_front(); statement, then you won't get undefined behaviour, because that reference remains valid until the referred-to element is removed from the container.

In your case, the pop appears to be the very last statement in the scope of the reference (a new one will be created/formed on each iteration of the while loop), so that doesn't appear to be an issue.

like image 153
Adrian Mole Avatar answered Nov 21 '25 08:11

Adrian Mole



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!