colorify.js

C++ Nuggets - My little array class

Sometimes I need to store a little collection of something. I usually use a C-style array and an accompanying length variable. This is very handy - it's fast to implement, works very fast as there are no allocations, minimal amount of pointer dereferences, and no redundant pieces.


Here goes:

void foo()
{
  int a[5];
  int len = 0;

  // push back
  a[len++] = x;
  //...
}

After some time time I get annoyed with writing too much code per single conceptual operation and scribble something like this:

template< typename T, int N >
struct array
{
  T a[N];
  int len;
  array() : len(0) {}
  void push_back( T v ) { a[len++] = v; }
  T& operator[] ( int i ) { return a[i]; }
};

This is great for little things that don't require any construction. Like primitive types. For proper classes that have constructor, copy constructors etc, we'd need at least these:
1. Take const reference parameters.
2. Not construct N instances on construction of our array class.
3. Construct or destruct T when the user expects it - on addition or removal

Like this:

template< typename T, int N >
struct array
{
  char a[ N * sizeof(T) ];
  int len;
  array() : len(0) {}
  T& at( int i ) { return *(T*)( a + i * sizeof(T) ); }
  void push_back( const T& v ) { at(len++).T(v); } // call copy constructor
  T& operator[] ( int i ) { return at(i); }
};

It's easy to extend it to a full fledged array with everything std::vector supports. And I write little extensions when the need arises. For example, I once wanted to erase an element, but didn't care for the order, so did something like this:

  void erase_unordered( int i ) {
    at(i) = at(--len);
    at(len).~T();
  }

This would probably be nicer with C++11 move semantics.

What I really think is that STL should provide this. They did add std::array in C++11 but it does not cover variable length like here. Maybe it warrants a separate class? not sure.

So, guys, do you hear me up there?








No comments:

Post a Comment