More tr1: Static Arrays

One of the old throwbacks to C in C++ is the notion of the “C-style array”: essentially a block of contiguous memory that you allocate either statically, or dynamically with malloc/free or new/delete. These structures were used in a time where efficiency was everything and programmers rode dinosaurs to work. In C++ there are many safe alternatives to the C-style array: vectors, lists, dequeues, etc. But sometimes you just want a simple, safe array to pass around. And that brings us to static arrays, C++ style :)

Check out the following code:

void foo()
{
// Initialize my array of three ints.
std::tr1::array<int, 3> myStaticArray;
myStaticArray[0] = 0;
myStaticArray[1] = 1;
myStaticArray[2] = 2;

// The [ ] operator behaves just like a traditional array: unchecked, dangerous.
for (unsigned i = 0; i < 3; ++i)
{
cout << myStaticArray[i] << endl;
}

// The array also offers safe alternatives. The at() method is a bounds-checked version of the [ ] operator. Also note the use of size().
for (unsigned i = 0; i < myStaticArray.size(); ++i)
{
cout << myStaticArray.at(i) << endl;
}
}

As you can see, there are safe alternatives to traditional array indexing, but the unchecked ways are still around in case you still need every ounce of speed out of your application.

Checked Arrays: another example of how modern C++ is safer and cleaner than traditional C. These, in conjunction with smart pointers, and a whole plethora of data structures and algorithms in the STL, make C++ a joy to work with. :)

About Bryan St. Amour

Why yes! I do own this place!
This entry was posted in Code and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>