自定义的分配编译问题
问题描述:
我有一个Matrix
类是个集合。数据类型被定义为以下:自定义的分配编译问题
行:
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;
};
的数据类型使用一个分配器,主要功能是:
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 version 4.7.2
和clang version 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
的情况下编译代码。
答
看起来就是了aligned_allocator <>有运营商==()。