c++ - 启用 -std=c++0x 时自定义分配器的编译问题

标签 c++ vector c++11 allocator

我有一个 Matrix 类,它是 Row 的集合。数据类型定义如下:

行:

template <typename Index>
class Row {
public:

    Row()
    {
        _index_vector = std::vector<Index, aligned_allocator<Index> > ();
    }

    Row& operator=( const Row& source )
    {
        //some copy logic here
        return *this;
    }

private:
    std::vector<Index, aligned_allocator<Index> >       _index_vector;
};

矩阵:

template <typename Index>
class Matrix {
public:
    typedef std::vector<Row<Index> > Rep;

    Matrix () : _m (0), _n (0)
    {}

    Matrix (size_t n, size_t m) :
            _m (m),
            _n (n)
    {
        _A = Rep (n);
    }

private:
    Rep     _A;
    size_t      _m;
    size_t      _n;
};

Row数据类型使用了一个allocator,主要功能有:

template <class T>
class aligned_allocator
{
public:
       //Other methods; members...

    pointer allocate ( size_type size, const_pointer *hint = 0 ) {
        pointer p;
        posix_memalign((void**)&p, 16, size * sizeof (T));

        return p;
    };

    void construct ( pointer p, const T& value ) {
        *p=value;
    };

    void destroy ( pointer p ) {
        p->~T();
    };

    void deallocate ( pointer p, size_type num ) {
        free(p);
    };
};

我用这个简单的程序来测试代码:

#include "types.h"

int main(int argc, char **argv)
{
    Matrix<int> AA (100, 100);
}

当我在没有 -std=c++0x 的情况下编译它时,它编译没有任何错误。但是,当启用 -std=c++0x 时,出现以下错误:

error: invalid operands to binary expression ('_Tp_alloc_type'
      (aka 'aligned_allocator<int>') and '_Tp_alloc_type')
        if (__x._M_get_Tp_allocator() == this->_M_get_Tp_allocator())

./types.h:26:17: note: in instantiation of member function 'std::vector<int, aligned_allocator<int> >::operator=' requested here
                _index_vector = std::vector<Index, aligned_allocator<Index> > ();

这可能是什么原因?以及可能的修复/解决方法。我正在使用 gcc 4.7.2 版clang 3.1 版

(抱歉代码太长了。)

最佳答案

错误消息实际上包含提示。我在这里稍微重新表述了它:

error: invalid operands [of type aligned_allocator<int>] to binary expression […] __x._M_get_Tp_allocator() == this->_M_get_Tp_allocator()

换句话说,您的分配器类型需要提供一个 operator == .

这是分配器要求的一部分(§17.6.3.5,表 28)。一直都是这样。但直到 C++11 分配器是无状态的并且 operator ==因此总是返回true ,因此标准库容器可能从未调用过运算符。这可以解释为什么代码编译时没有 -std=++0x .

关于c++ - 启用 -std=c++0x 时自定义分配器的编译问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16126133/

相关文章:

c++ - "premature"销毁可能吗?

c++ - 错误 C2065 : 'cout' : undeclared identifier

c++ - 为枚举索引数组重载 std::get

c++ - 在 QuantLib 日期类和 C++11/boost Chrono 上

c++ - 如何使用 C++11 std::bind 绑定(bind)类中同名的成员函数之一

c++ - 交叉编译openCV应用

c++ - linux下从HTML中提取关键字到C++

c++ - 使用对 vector 的 vector ?

c++ - 如何将数字列表从字符串复制到 C++ vector

c++ - C++中 vector vector 中索引的最有效排序