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

13

是否有一种方法可以使用attribute((aligned))将STL容器的对齐方式强制为特定字节?目标编译器不是Microsoft Visual C++。

是否存在任何库,可以提供具有特定显式向量化(例如SSE)的STL算法的专门模板。我感兴趣的编译器是g ++,Intel和IBM XL。

5个回答

14

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

但只需将对齐属性添加到元素类型中可能就足够了。这超出了标准的范围,因此您需要查阅编译器文档并尝试。


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();
     }
};

这里唯一缺少的是 aligned_mallocaligned_reallocaligned_free。你可以自己实现它们(应该不难),或者在互联网上找到这些函数的版本(我在OGRE引擎中看到过至少一个)。

1
@Anycorn,你有没有实现这个功能?完成Kornel Kisielewicz的示例似乎会很棒,因为我在其他任何在线资源中都没有看到好的示例。 - David Doria
在我看来,C++17的std::aligned_alloc 应该可以解决问题,它应该可以与std::free()和std::realloc()一起使用。 - Dudly01

3

你已经得到了一些好的答案,但是值得补充的是,C++ 0x 包括一个 std::align(),这应该使实现这样的事情变得更容易。


1
有没有使用这个作为分配器的示例? - David Doria

2
你需要一个返回对齐存储的自定义分配器,这应该可以解决你的问题。

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接