【问题标题】:C++ STL data structure alignment, algorithm vectorizationC++ STL数据结构对齐、算法向量化
【发布时间】:2011-01-03 03:26:20
【问题描述】:

有没有办法强制 STL 容器对齐到特定字节,也许使用 attribute((aligned))?目标编译器不是 Microsoft Visual C++。

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

【问题讨论】:

    标签: c++ stl alignment vectorization


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      您需要传递一个自定义分配器。你可以很容易地在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 引擎中至少看到过一个)。

      【讨论】:

      • @Anycorn,你有没有实现过这个?在这里完成 Kornel Kisielewicz 的示例似乎很棒,因为我在网上其他任何地方都没有看到这样的好示例。
      • @kornel-kisielewicz 在我看来,C++17 std::aligned_alloc should do the trick 应该可以与 std::free() 和 std::realloc() 一起使用。
      【解决方案3】:

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

      【讨论】:

      • 有没有在某处使用这个作为分配器的例子?
      【解决方案4】:

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

      【讨论】:

        【解决方案5】:

        您可以使用boost::alignment::aligned_allocator,而不是编写自己的分配器,如suggested before

        【讨论】:

          猜你喜欢
          • 2013-06-03
          • 2023-03-23
          • 1970-01-01
          • 2014-02-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-02-09
          相关资源
          最近更新 更多