Below are some code which use erase in 'for' cycle.
It want to remove a element which meet the condition.
typedef std::vector<struct pollfd> PollFdList;
PollFdList poll_fds_;
for (PollFdList::iterator pfd = poll_fds_.begin(); pfd != poll_fds_.end(); ++pfd)
{
if (pfd->fd == fd)
{
poll_fds_.erase(pfd);
break;
}
}
Does the code work?, i.e. there is no logic error?
I am not sure about this.
I think a better way is like below:
for (PollFdList::iterator pfd = poll_fds_.begin(); pfd != poll_fds_.end(); ++pfd)
{
if (pfd->fd == fd)
{
pfd = poll_fds_.erase(pfd);
break;
}
}
The difference between them is the iterator pfd is explictly updated to point to the new location of the element that followed the last element erased by the function call.
Yes.
The iterator pfd is invalidated by poll_fds_.erase(pfd);
after that, if we evaluate ++pfd it would engender undefined behaviour.
However, because of the break immediately after the call to erase(), the invalidated iterator is never used again; this is therefore fine.