4

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

Is there a way to detect this kind of error at compile 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
ColdCat
  • 1,192
  • 17
  • 29
  • Maybe some static analysis tool based on that new clang stuff can, but just some of your own C++ code can't. – PlasmaHH Mar 15 '13 at 13:56
  • 4
    How can you describe this as legacy code when the use of the keyword `auto` is in the code? – Ed Heal Mar 15 '13 at 13:58
  • at runtime: you can use a "safe" STL that checks the iterators. – Karoly Horvath Mar 15 '13 at 13:59
  • simple: don't use `std::distance` for `vector`. It doesn't make sense anyway. –  Mar 15 '13 at 14:00
  • In GCC, use `-D_GLIBCXX_DEBUG`. In Visual Studio, compile in debug mode. – Benjamin Lindley Mar 15 '13 at 14:02
  • possible duplicate of [Using a checked STL implementation, anything available for free?](http://stackoverflow.com/questions/2567997/using-a-checked-stl-implementation-anything-available-for-free) – Benjamin Lindley Mar 15 '13 at 14:05
  • 1
    @EdHeal: 1) He could have simplified the code for posting here. 2) It could be legacy code that had a C++11 update run over it. It could still be called legacy. 3) By the definition of some people, legacy code means "doesn't have unit tests". Even new code can be immediately legacy. 4) If you don't like that definition, you might still consider code written to a legacy architecture to be legacy code, even if that bit of code is new. – Sebastian Redl Mar 15 '13 at 15:42

1 Answers1

3

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

    std::vector<int>
      v1, v2 ;

    std::distance( v1.begin(), v2.end() ) ;

I see this errors when I run:

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 thing for Visual Studio.

Community
  • 1
  • 1
Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740