std::align and std::aligned_storage for aligned allocation of memory blocks

后端 未结 2 2099
傲寒
傲寒 2020-12-14 12:42

I\'m trying to allocate a block of memory of size size which needs to be Alignment aligned where the size may not be defined at compile time. I kno

2条回答
  •  情话喂你
    2020-12-14 13:01

    If it HAS TO BE a C++11 solution, then ignore this answer.

    If not... I don't know if you already know this, but here is one option:

    void * aligned_malloc( size_t size, size_t alignement )
    {
        void * p = malloc( size + --alignement );
        void * p1 = (void*)( ( (size_t)p + alignement ) & ~alignement );
    
        ((char*)p1)[ -1 ] = (char)((char*)p1 - (char*)p);
    
        return p1;
    }
    
    void aligned_free( void * pMem )
    {
        char * pDelete = (char*)pMem - ((char*)pMem)[ -1 ];
        free( pDelete );
    }
    

    Perhaps malloc and free are not 100% portable, but it's easy to handle such cases with preprocessor directives.

提交回复
热议问题