c++ - 自定义分配器和默认成员

标签 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 & 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.

最佳答案

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

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

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

关于c++ - 自定义分配器和默认成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12516085/

相关文章:

c++如何从派生类调用派生类中重载的模板类函数?

c++ - 强制在编译时评估 constexpr

c++ - uninitialized_copy/fill(In first, In last, For dest, A &a) 是 c++ 标准中的疏忽吗?

C++程序可以在linux下运行,但不能在windows下运行

c++ - 改变击键速度 C++

c++ - 自定义分配器无法重新绑定(bind)到其他类型

c++ - 什么是空 `std::allocator` ?即 : `std::allocator<void>`

allocator - 在 Zig lang 中分配通用结构

c++ - 使用不同分配器分配的内存

c++ - 静态函数和非虚拟方法可以被覆盖吗?什么是静态多态?