Search code examples
c++stldynamic-memory-allocation

posix_memalign for std::vector


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

sizeof(std::vector<type>(n)) 

without actually creating a new vector.

Thanks


Solution

  • 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)
        { 
            free(pPtr);
        }
    
        // ...
    };
    

    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.