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

0xF*_*xFF 3 c++ vector allocator c++11

我有一个Matrix类是Rows 的集合.数据类型定义如下:

行:

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;
};
Run Code Online (Sandbox Code Playgroud)

矩阵:

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;
};
Run Code Online (Sandbox Code Playgroud)

Row数据类型使用的分配器,主要功能是:

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);
    };
};
Run Code Online (Sandbox Code Playgroud)

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

#include "types.h"

int main(int argc, char **argv)
{
    Matrix<int> AA (100, 100);
}
Run Code Online (Sandbox Code Playgroud)

当我没有编译它时-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> > ();
Run Code Online (Sandbox Code Playgroud)

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

(对不起冗长的代码.)

Kon*_*lph 6

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

错误:[类型aligned_allocator<int>] 无效的操作数到二进制表达式[...]__x._M_get_Tp_allocator() == this->_M_get_Tp_allocator()

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

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