Discussion
Team LiB
Previous Section Next Section

Discussion

There are three major kinds of invalid objects:

  • Destroyed objects: Typical examples are automatic objects that have gone out of scope and deleted heap-based objects. After you call an object's destructor, its lifetime is over and it is undefined and generally unsafe to do anything with it.

  • Semantically invalidated objects: Typical examples include dangling pointers to deleted objects (e.g., a pointer p after a delete p;) and invalidated iterators (e.g., a vector<T>::iterator i after an insertion at the beginning of the container the iterator refers into). Note that dangling pointers and invalidated iterators are conceptually identical, and the latter often directly contain the former. It is generally undefined and unsafe to do anything except assign another valid value to an invalidated object (e.g., p = new Object; or i = v.begin();).

  • Objects that were never valid: Examples include objects "obtained" by forging a pointer (using reinterpret_cast, see Item 92), or accessing past array boundaries.

Be aware of object lifetimes and validity. Never dereference an invalid iterator or pointer. Don't make assumptions about what delete does and doesn't do; freed memory is freed, and shouldn't be subsequently accessed under any circumstances. Don't try to play with object lifetime by calling the destructor manually (e.g., obj.~T()) and then calling placement new. (See Item 55.)

Don't use the unsafe C legacy: strcpy, strncpy, sprintf, or any other functions that do write to range-unchecked buffers, and/or do not check and correctly handle out-of-bounds errors. C's strcpy does not check limits, and [C99]'s strncpy checks limits but does not append a null if the limit is hit; both are crashes waiting to happen and security hazards. Use more modern, safer, and more flexible structures and functions, such as those found in the C++ standard library (see Item 77). They are not always perfectly safe (for the sake of efficiency), but they are much less prone to errors and can be better used to build safe code.

    Team LiB
    Previous Section Next Section