Home > Enterprise >  Reference list element then popping it, is it undefined behaviour?
Reference list element then popping it, is it undefined behaviour?

Time:11-26

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?

CodePudding user response:

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.

CodePudding user response:

Looks valid to me.
std::list::pop_front() decrements the size.
std::list::empty() returns true when the begin and end iterators compare equal. Size is 0 when the distance from begin to end is 0.
It's all well-defined behavior, as far as I know.

  • Related