Bound iterator invalidation #697
Kubiyak
started this conversation in
Suggestions
Replies: 1 comment
-
To what extent can this be done already without C++ language changes? |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I made the same suggestion to the carbon-language folks:
One common and pernicious issue with c++ is indirect and unexpected iterator invalidation. This issue turns up in large projects where multiple developers work on the same codebase and are not perfectly aware of what other developers are doing.
for (auto itr = my_map.begin(); itr != my_map.end(); ++itr ) {
some_function_which_unexpectedly_deletes_elem_pointed_to_by_itr(args...);
}
My suggestion is to bound this sort of problem and at least obtain a proper runtime exception in this situation rather than UB.
There are several ways to accomplish this. The simplest low tech method is to support some language level context manager which can place std::map or even user defined classes into a "do not allow sub-object deletion" mode
iterator_invalidation_guard(my_map) {
for (auto itr = my_map.begin(); itr != my_map.end(); ++itr ) {
some_function_which_unexpectedly_deletes_elem_pointed_to_by_itr(args...); // throws if anything is deleted from my_map
}
}
The goal is to turn UB into a proper exception hopefully with sufficient context to be able to evaluate the problem and fix.
iterator_invalidation_guard is not a typical RAII type although it is an RAII type. No references or pointers are allowed to this and it MUST be constructed on the stack and its lifetime must end at function return: It can be passed as an argument to functions called within its lifetime but it cannot be returned from the function in which it was constructed.
I think formalizing such a construct is a useful tool for bounding a number of situations which can result in UB and is another tool for developers to use to write safe code.
Beta Was this translation helpful? Give feedback.
All reactions