RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Spruce Up Your Built-in Arrays

Built-in arrays provide superior performance, but the trick is to use them without compromising STL compatibility. This solution will teach you to use built-in arrays properly and how to create an array whose dimensions are determined at runtime without having to resort to hefty dynamic memory allocation.

++ pundits recommend that you replace built-in arrays with st::vector across the board. Sometimes however, built-in arrays are unavoidable due to their unsurpassed efficiency or because your app must interact with external software e.g., a relational database or an XML schema. In the following sections I will present two techniques for enhancing this mundane feature: an array wrapper template, and a variable length array. When used judiciously, these enhancements enable you to use built-in arrays without sacrificing STL compatibility and without resorting to manual memory management, respectively.

How to use built-in arrays without compromising STL compatibility? Also, how to create an array whose dimensions are determined at runtime without the pains of dynamic memory allocation?

Use an array wrapper template and C99's variable length arrays, respectively.

Problem Analysis
When you need a container that grows and shrinks dynamically, st::vector is unquestionably the right choice. However, sometimes st::vector is used instead of a built-in array only for the sake of interoperability with other Standard Library components. Performance-wise, this technique isn't ideal: st::vector involves complex construction and destruction operations, it allocates elements on the free-store (even when their number is fixed and known at compile-time), and it isn't exactly a lightweight class. What you really want is the compactness and speed of built-in arrays, while still benefiting from an STL-like interface. You can achieve this by using a wrapper class template.

Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date