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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With