是否有一种方法可以使用attribute((aligned))将STL容器的对齐方式强制为特定字节?目标编译器不是Microsoft Visual C++。
是否存在任何库,可以提供具有特定显式向量化(例如SSE)的STL算法的专门模板。我感兴趣的编译器是g ++,Intel和IBM XL。
是否有一种方法可以使用attribute((aligned))将STL容器的对齐方式强制为特定字节?目标编译器不是Microsoft Visual C++。
是否存在任何库,可以提供具有特定显式向量化(例如SSE)的STL算法的专门模板。我感兴趣的编译器是g ++,Intel和IBM XL。
使用STL容器时,您可以通过一个可选的模板参数提供自己的分配器。我不建议从头编写整个分配器,但您可以编写一个仅是new
和delete
的包装器,确保返回的内存满足您的对齐需求。(例如,如果您需要具有16字节对齐的n
字节,则使用new
分配n + 15
字节,并返回该块中第一个16字节对齐地址的指针。)
但只需将对齐属性添加到元素类型中可能就足够了。这超出了标准的范围,因此您需要查阅编译器文档并尝试。
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_malloc
,aligned_realloc
和 aligned_free
。你可以自己实现它们(应该不难),或者在互联网上找到这些函数的版本(我在OGRE引擎中看到过至少一个)。你已经得到了一些好的答案,但是值得补充的是,C++ 0x 包括一个 std::align()
,这应该使实现这样的事情变得更容易。
std::aligned_alloc
应该可以解决问题,它应该可以与std::free()和std::realloc()一起使用。 - Dudly01