Domanda

I have a Matrix class which is a collection of Rows. The data types are defined as following:

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;
};

Matrix:

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;
};

The Row data type uses an allocator, the main functions are:

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);
    };
};

I use this simple program to test the code:

#include "types.h"

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

When I compile this without -std=c++0x, it compiles without any errors. However when -std=c++0x is enabled, I get the following error:

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> > ();

What could be the reason for this? and the possible fix/workaround. I am using gcc version 4.7.2 and clang version 3.1.

(sorry for the lengthy code.)

È stato utile?

Soluzione

The error message actually contains the hint. I’ve reformulated it slightly here:

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

In other words, your allocator type needs to provide an operator ==.

This is part of the allocator requirements (§17.6.3.5, table 28). This has always been the case. But until C++11 allocators were stateless and operator == consequently always returned true, so the standard library containers probably never called the operator. This would explain why the code compiles without -std=++0x.

Altri suggerimenti

Looks like it wants aligned_allocator<> to have operator ==().

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top