Discussion
Team LiB
Previous Section Next Section

Discussion

Buffer overruns and security flaws are, hands down, a front-running scourge of today's software. Silly limitations due to fixed-length arrays are a major annoyance even when within the limits of correctness. Most of these are caused by using bare C-level facilitiessuch as built-in arrays, pointers and pointer arithmetic, and manual memory managementas a substitute for higher-level concepts such as buffers, vectors, or strings.

Here are some reasons to prefer the standard facilities over C-style arrays:

  • They manage their own memory automatically: No more need for fixed buffers of "longer than any reasonable length" ("time bombs" is a more accurate description), or for frantic realloc'ing and pointer adjustment.

  • They have a rich interface: You can implement complex functionality easily and expressively.

  • They are compatible with C's memory model: vector and string::c_str can be passed to C APIsin both read and write modes, of course. In particular, vector is C++'s gateway to C and other languages. (See Items 76 and 78.)

  • They offer extended checking: The standard facilities can implement (in debug mode) iterators and indexing operators that expose a large category of memory errors. Many of today's standard library implementations offer such debugging facilitiesuse them! (Run, don't walk, to Item 83.)

  • They don't waste much efficiency for all that: Truth be told, in release mode vector and string favor efficiency over safety when the two are in tension. Still, all in all, the standard facilities offer a much better platform for creating safe components than do bare arrays and pointers.

  • They foster optimizations: Modern standard library implementations include optimizations that many of us mere mortals have never thought of.

An array can be acceptable when its size really is fixed at compile time (e.g., float[3] for a three-dimensional point; switching to four dimensions would be a redesign anyway).

    Team LiB
    Previous Section Next Section