How to detect poor use of an iterator during compilation or runtime

I just found in some legacy code a big abuse of std :: distance between iterators of different containers. Something like code. Now I'm afraid that someone might have made the same mistake in another part of the code.

Is there a way to detect such an error during compilation or runtime?

// bad code to explain the problem std::vector<int> v1={1}; auto iterv1=v1.begin(); std::vector<int> v2=v1; int nDist=std::distance(v2.begin(),iterv1); // error distance calculated between 2 containers 
+4
source share
1 answer

So, if I try this example and in g++ compile with -D_GLIBCXX_DEBUG :

  std::vector<int> v1, v2 ; std::distance( v1.begin(), v2.end() ) ; 

I see these errors on startup:

 error: attempt to compute the different between two iterators from different sequences. 

There is more output, but I think this should cover it. This previous thread covers the same for Visual Studio .

+3
source

Source: https://habr.com/ru/post/1469526/


All Articles