EPOC   SDK Home Glossary Indexes Previous Next Up

About the range checking wrapper for C++ arrays


Contents


Overview

The C++ language provides fixed length arrays, for example:

    TInt array[8];

an array of eight TInt elements.

It can often be convenient to use these arrays in EPOC applications whenever the number of elements is fixed and known at compile time.

The main disadvantage of using C++ arrays is that there is no automatic checking of index values. There is nothing at either compile time or run time to prevent illegal accesses such as occurs in this code fragment:

    TInt array[8];
    for (TInt ix = 0,ix <= 8, ix++)
          {
          array[ix] = ix;
          }

The assignment array[8] = 8; will be executed, even though the location array[8] is outside the bounds of the array.

Introduced in ER5, the templated class TFixedArray<class T,TInt S>, defined in e32std.h, is a thin wrapper for C++ arrays.

The major benefits of using this class over a basic C++ array are the provision of range-checked indexing and support for object deletion. There is no runtime penalty for using this class if debug-only range-checking is used.

C++ arrays can always be replaced with a TFixedArray<class T,TInt S>. For example:

    TChar iSeparators[EMaxSeparators];
    CCoeControl* iControls[ENumControls];

becomes

    TFixedArray<TChar,EMaxSeparators> iSeparators;
    TFixedArray<CCoeControl*,ENumControls> iControls;

Note that the contained class must have a default constructor. The array can also be initialised from a C++ array (using a bitwise copy).


Using the range checking wrapper

Instead of declaring a C++ array directly:

    TTest array[4];

use:

    TFixedArray<TTest,4> array;

The array can be initialised either at construction time or by using the Copy() member function after construction.

For example:

    ...
    const TTest data[] = {TTest(1),TTest(2),TTest(3),TTest(4)};
    ...
          // initialise at construction time
    TFixedArray<TTest,4> array(&data[0],4);
    ...
          // or later using Copy()
    TFixedArray<TTest,4> array;
    array.Copy(&data[0],4);
    ...

Accesses can be checked for legality using the At() function or the operator[].

The At() function checks for a legal access in both a release build and a debug build while the operator[] just checks for legal access in a debug build.

The following code fragments are taken from the eufixarr example which can be found in the \Epoc32ex\E32 set of examples. The call to the SetValue() member function of the TTest object in the second element of the array is legal:

    array.At(1).SetValue(100);

but the following attempt to change the fifth element causes a panic; in this example, there are only four elements:

    array.At(5).SetValue(100); // panics
EPOC       SDK Home Glossary Indexes Previous Next Up