自定义分配器和默认成员

Custom allocator & default member

本文关键字:成员 默认 分配器 自定义      更新时间:2023-10-16

为什么这段代码不编译?

#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和reference_const类型。但是,根据 cpp首选项,这些成员都是可选的。似乎如果 STL 不使用allocator_trait(我使用 -std=c++11 进行编译,所以它应该很好)。

知道吗?

[编辑] 在叮当声中,错误是:

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.
这是

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

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

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