【发布时间】:2016-09-08 01:21:26
【问题描述】:
我正在研究/玩分配器,试图了解它是如何工作的。但是我在尝试实现接受分配器的琐碎容器时遇到了问题。现在我结束了:
template<class T, class Allocator =std::allocator<T>> class Container {
public:
using allocator_type = Allocator;
using value_type = T;
using pointer = typename std::allocator_traits<allocator_type>::pointer;
using reference = value_type&;
using size_type = std::size_t;
Container( size_type n =0 , const allocator_type& allocator =allocator_type() ){
std::cout << "ctor" << std::endl;
allocator.allocate(n);
};
};
int main(int argc, const char* argv[]){
Container<int> c {5};
return 0;
}
它给了我一个错误member function 'allocate' not viable: 'this' argument has type 'const allocator_type' (aka 'const std::__1::allocator<int>'), but function is not marked const
请问如何解决这个错误?我错过了什么吗? 我打算稍后使用特征,但想先使用旧方法使其工作。
【问题讨论】:
-
标记
const的不是函数而是allocator。您可能想看看 libc++、libstdc++ 是如何以std::vector之类的方式实现的。 -
标准容器通常使用这个 const 引用来初始化它们自己的成员(或基类),而不是在这个成员上调用 allocate。