自定义分配器和默认成员
Custom allocator & default member
为什么这段代码不编译?
#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
,则此代码将编译。
相关文章:
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 基类中的默认析构函数禁用子类中的移动构造函数(如果有成员)
- C++向量默认为成员参数
- 在 C++ 中声明 const 对象需要用户定义的默认构造函数.如果我有一个可变成员变量,为什么不呢?
- 强制使用默认构造函数对成员进行未初始化的声明
- 在 C++ 中,默认情况下构造函数为类的数据成员提供的值是多少?
- 用作默认参数的静态成员会导致无法解析的外部
- 为什么在使用指针时不采用类成员的默认值,而不是直接实例化对象时?
- 具有外部定义的默认特殊成员函数
- C++中未初始化成员布尔变量的默认值是多少?
- 两个成员,在Base中默认初始化,可能在Derived中非默认初始化
- 声明成员对象而不调用其默认构造函数
- 将私有数据成员作为默认参数传递给该类的公共方法时出错
- 结构中的默认成员值或默认构造函数参数
- C++11 默认类成员初始化与初始值设定项列表同时
- POD成员默认初始化无括号
- 初始化类成员 - 默认值还是成员初始化列表?
- 具有类成员默认值的 C++11 默认构造函数行为
- 模板成员默认初始化
- 类 POD 成员默认初始化与零初始化与无初始化