Static vector

Let's start with a moment of silence for our dear friend:

char myBuffer[64];

Ever wondered how nice it would be to just use static, zero allocation cost stack memory without even thinking about it? But, usually, it involves nasty things like direct pointer manipulation, imperative loops which just eagerly wait for you to make a mistake and trick you into yet another debugging session.

Well, good news is - now you don't have to. Templatious has two classes that deal with this:

  • templatious::StaticBuffer
  • templatious::StaticVector

Let's try it!

templatious::StaticBuffer<int,16> buffer;

auto v = buffer.getStaticVector();

What happened here? First, we declare buffer variable, that has enough stack memory in it to hold 16 integers. Second, we make one static vector out of that. You don't have to care about it's API too much because it also satisfies collection adapter interface so you can use it with collection adapter.

Now, why do we need buffer and we don't write static vector with its own memory explicitly?

There are two benefits:

  • We can have a buffer and chunk it into vectors in a very explicit manner.
  • Static vector only needs a type, pointer and size, therefore, it can be used with any memory out there, not just stack memory.

So, let's demonstrate the control we get over our buffer:

templatious::StaticBuffer<int,64> buffer;

auto a = buffer.getStaticVector(16);
auto b = buffer.getStaticVector(16);
auto c = buffer.getStaticVector(16);
auto d = buffer.getStaticVector();

SA::add(a,1,2,3,4,5,6,7,8);
SA::add(b,a);
SA::add(c,b);
SA::add(d,c);

We create four vectors, each can contain 16 integers. We try to write more - it throws. For vectors a,b,c we specify capacity explicitly, however, on d we call method without capacity - this simply takes the remaining memory in the buffer. After that point, if we try to get any more vectors, exception will be thrown (or, if we ask for capacity that is too big for the buffer).

With the vectors created we can do anything we can do with Static Adapter. It can be used with the rest of templatious ecosystem.

When the created vectors go out of scope they destroy the elements they constructed. However, vectors assume no responsibility for freeing the memory, after they are done and destroyed the memory used is free for reuse.

This means, that you can create a static vector out of arbitrary chunk of memory:

void* mem = malloc(16 * sizeof(int));

{ // make sure vector is destroyed in this scope
    templatious::StaticVector<int> v(
        reinterpret_cast<int*>(mem),16);

    SA::add(v,SF::seqL(16));
}

free(mem);

Perfectly legal, although, now it is our responsibility to take care of the memory. Also, static buffer assures memory is aligned by using std::aligned_storage.