Take the 2-minute tour ×

Is there a way to posix_memalign a std::vector without creating a local instance of the vector first? The problem I'm encountering is that I need to tell posix_memalign how much space to allocate and I don't know how to say


without actually creating a new vector.


share|improve this question
add comment

1 Answer

up vote 8 down vote accepted

Well, there are two sizes here. The vector itself is typically no more than a pointer or two to some allocated memory, and unsigned integers keeping track of size and capacity. There is also the allocated memory itself, which is what I think you want.

What you want to do is make a custom allocator that the vector will use. When it comes time, it will use your allocator and you can have your own special functionality. I won't go over the full details of an allocator, but the specifics:

template <typename T>
struct aligned_allocator
    // ...

    pointer allocate(size_type pCount, const_pointer = 0)
        pointer mem = 0;
        if (posix_memalign(&mem, YourAlignment, sizeof(T) * pCount) != 0)
            throw std::bad_alloc(); // or something

        return mem;

    void deallocate(pointer pPtr, size_type)

    // ...

And then you'd use it like:

typedef std::vector<T, aligned_allocator<T> > aligned_T_vector;

aligned_T_vector vec;
vec.push_back( /* ... */ ); // array is aligned

But to reiterate the first point, the size of a vector is the same regardless of how many elements it's holding, as it only points to a buffer. Only the size of that buffer changes.

share|improve this answer
add comment

Your Answer


