C++ STL数据结构对齐,算法向量化

Any*_*orn 13 c++ stl alignment vectorization

有没有办法使用属性((对齐))强制STL容器对齐到特定字节?目标编译器不是Microsoft Visual C++.

哪些库(如果有的话)提供具有特定显式向量化的STL算法的专用模板,例如SSE.我感兴趣的编译器是g ++,Intel和IBM XL.

Adr*_*thy 13

使用STL容器,您可以通过可选的模板参数提供自己的分配器.我不建议从头开始编写一个完整的分配器,但你可以编写一个只是一个包装器new,delete但确保返回的内存满足你的对齐要求.(例如,如果需要n具有16字节对齐的字节,则使用new分配n + 15字节并返回指向该块中第一个16字节对齐地址的指针.)

但是将alignment属性添加到元素类型可能就足够了.这超出了标准的范围,因此您必须检查编译器文档并进行尝试.


Kor*_*icz 7

您需要传递自定义分配器.你可以std::allocator很容易地构建一个:

template <typename T, size_t TALIGN=16, size_t TBLOCK=8>
class aligned_allocator : public std::allocator<T>
{
public:
     aligned_allocator() {}
     aligned_allocator& operator=(const aligned_allocator &rhs){
         std::allocator<T>::operator=(rhs);
         return *this;
     }

     pointer allocate(size_type n, const void *hint){
         pointer p = NULL;
         size_t count = sizeof(T) * n;
         size_t count_left = count % TBLOCK;
         if( count_left != 0 )
         {
             count += TBLOCK - count_left;
         }
         if ( !hint )
         {
             p = reinterpret_cast<pointer>(aligned_malloc(count,TALIGN));
         }else{
             p = reinterpret_cast<pointer>(aligned_realloc((void*)hint,count,TALIGN));
         }
         return p;
     }

     void deallocate(pointer p, size_type n){
         aligned_free(p);
     }

     void construct(pointer p, const T &val){
         new(p) T(val);
     }

     void destroy(pointer p){
         p->~T();
     }
};
Run Code Online (Sandbox Code Playgroud)

这里唯一缺少的是aligned_malloc,aligned_reallocaligned_free.你需要自己实现它们(不应该那么难),或者在互联网上找到那些版本(我在OGRE引擎中至少看过一个版本).