自定义分配器&默认会员

时间:2012-09-20 15:37:57

标签: c++ allocator

为什么不编译this code

#include <cstdlib>
#include <list>

template < typename Type >
class Allocator {
public:
    using value_type = Type;
public:
    template < typename Other >
    struct rebind { using other = Allocator< Other >; };
public:
    Type * allocate( std::size_t n ) { return std::malloc( n ); }
    void deallocate( Type * p, std::size_t ) throw ( ) { std::free( p ); }
};

int main( void ) {
    std::list< void *, Allocator< void * > > list;
    return 0;
}

似乎需要指针,引用,pointer_const&amp; reference_const类型。但是,根据cppreference,这些成员都是可选的。似乎STL没有使用allocator_trait(我正在使用-std = c ++ 11进行编译,所以它应该是好的)。

有什么想法吗?

[edit]在clang上,错误是:

user@/tmp > clang++ -std=c++11 test.cc
In file included from test.cc:2:
In file included from /usr/lib/gcc/i686-pc-linux-gnu/4.7.1/../../../../include/c++/4.7.1/list:63:
/usr/lib/gcc/i686-pc-linux-gnu/4.7.1/../../../../include/c++/4.7.1/bits/stl_list.h:449:40: error: no type named 'pointer' in 'Allocator<void *>'
      typedef typename _Tp_alloc_type::pointer           pointer;
              ~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~
test.cc:17:46: note: in instantiation of template class 'std::list<void *, Allocator<void *> >' requested here
    std::list< void *, Allocator< void * > > list;
                                             ^
In file included from test.cc:2:
In file included from /usr/lib/gcc/i686-pc-linux-gnu/4.7.1/../../../../include/c++/4.7.1/list:63:
/usr/lib/gcc/i686-pc-linux-gnu/4.7.1/../../../../include/c++/4.7.1/bits/stl_list.h:450:40: error: no type named 'const_pointer' in 'Allocator<void *>'
      typedef typename _Tp_alloc_type::const_pointer     const_pointer;
              ~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~
/usr/lib/gcc/i686-pc-linux-gnu/4.7.1/../../../../include/c++/4.7.1/bits/stl_list.h:451:40: error: no type named 'reference' in 'Allocator<void *>'
      typedef typename _Tp_alloc_type::reference         reference;
              ~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~
/usr/lib/gcc/i686-pc-linux-gnu/4.7.1/../../../../include/c++/4.7.1/bits/stl_list.h:452:40: error: no type named 'const_reference' in 'Allocator<void *>'
      typedef typename _Tp_alloc_type::const_reference   const_reference;
              ~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~
4 errors generated.

1 个答案:

答案 0 :(得分:2)

这是GCC C ++标准库中的一个错误。

使用列表时,它们没有通过allocator_traits正确包装对分配器的访问。

但是,他们确实正确地实现了向量。如果您使用std::vector而不是std::list,则会编译此代码。