Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About invalidating iterators

Tags:

c++

STL containers have the problem that iterators can be invalidated when the container changes. Would it be possible for the container to announce that it has changed by adding a call has_changed()?

It is common to query empty() before certain operations. If the container set a bool on operations that would affect iterators like insert() or erase() then it would be possible to query has_changed() before reusing an iterator.

Crazy?

EDIT Thanks for a bunch of good replies and food for thought. I wish I could award more than one winner.

like image 834
Newton Falls Avatar asked Dec 04 '22 22:12

Newton Falls


1 Answers

Kinda crazy, if well intentioned.

I think the main problem with that is how does a container know when it has "unchanged"? In other words, something is erased and the "changed" flag is set. What is the precipitating event whereby it resets the flag because it is back to a normal or stable state? It is really the iterators rather than the container that are in an invalid state.

I think for this to work at all iterators would need to be much, much smarter than they currently are and operate more like Observers to the container. The container could send an event to registered iterators that it has changed and they could check their own state before attempting an operation. But even this has so many holes it would probably lead to a bigger mess than what you are trying to solve.

like image 146
Duck Avatar answered Jan 02 '23 00:01

Duck