[Insight-developers] Using alloca

Williams, Norman K norman-k-williams at uiowa.edu
Tue Mar 12 14:32:25 EDT 2013


I can't think of a single reason in ITK to use alloca. Pretty much every use case for alloca can be implemented using C++ language features in a more robust manner.

Maybe it's unfair to say, but I think that the only reason it hasn't fallen out of use entirely is the esteem in which it is held by certain programmers associated with the GNU project. That's the one place it crept into VTK -- a bison-generated parser they've been modifying for years.

The following has been a workaround I've used since C++ hasn't supported dynamically sized arrays in the past -- I believe it is a gnu extension (that, by the way, uses alloca under the covers). Of course, in most cases, it is preferable to use a STL container.  I don't remember who said it first but it's true: Arrays are to data what goto is to code.

It is very nearly as efficient as raw array access, and the actual array is on the heap:

#include <cstddef>

template <typename TElement>
class DynArray
{
public:
  typedef std::size_t size_type;
  DynArray(size_type numElements) : m_Size(numElements)
    {
      this->m_Array = new TElement[numElements];
    }
  ~DynArray()
    {
      delete [] this->m_Array;
    }
  TElement &operator[](size_type idx)
    {
      if(idx > this->m_Size)
        {
        throw;
        }
      return this->m_Array[idx];
    }
  const TElement &operator[](size_type idx) const
    {
      if(idx > this->m_Size)
        {
        throw;
        }
      return this->m_Array[idx];
    }
private:
  TElement *m_Array;
  size_type m_Size;
};


--
Kent Williams norman-k-williams at uiowa.edu





On 3/12/13 7:54 AM, "Bradley Lowekamp" <blowekamp at mail.nih.gov<mailto:blowekamp at mail.nih.gov>> wrote:

Hello,

I am thinking about using the "alloca" function in some code I'm working on for ITK, and wonder what other people think of it or others experience...



More information about the Insight-developers mailing list