Suppose I've an empty list L. Currently if I run L.front(), it will merrily execute returning a garbage value. Is there some option I can turn on such that executing this would throw an exception or result in an assertion failure?
Thanks
Suppose I've an empty list L. Currently if I run L.front(), it will merrily execute returning a garbage value. Is there some option I can turn on such that executing this would throw an exception or result in an assertion failure?
Thanks
Use empty()
to check if the list is empty. size()
is not good here because it could have linear runtime. See more details in Effective STL. empty()
has constant runtime and it is a standard way.
MSVC checked iterators ( on by default )
If you are using Visual C++ 2010 (and probably earlier versions) then you can enable secure SCL and iterator debugging by using these two macros:
#define _SECURE_SCL 1
#define _HAS_ITERATOR_DEBUGGING 1
The other standard libraries may have that too.
Edit: Just as has been suggested, there is a single macro in VC2010, that is _ITERATOR_DEBUG_LEVEL
which has 3 levels defined like this:
#if _HAS_ITERATOR_DEBUGGING
#define _ITERATOR_DEBUG_LEVEL 2
#elif _SECURE_SCL
#define _ITERATOR_DEBUG_LEVEL 1
#else
#define _ITERATOR_DEBUG_LEVEL 0
#endif
Some standard libraries do offer such an option. You'd need to consult the documentation and/or code foryour particular implementation/compiler in order to determine its characteristics and how to enable it.
Alternately you could use a memory checker like valgrind or Purify instead of doing it in the library level.