c++ - trivial allocator aware container? -
i studying/playing allocators trying understand how works. run problems trying implement trivial container accepts allocator. ended this:
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; } it gives me error member function 'allocate' not viable: 'this' argument has type 'const allocator_type' (aka 'const std::__1::allocator<int>'), function not marked const
how fix error, please? missing ? intend use traits later make work using old way first.
your line
allocator.allocate(n); attempts call allocate method of allocator, not defined const method. if look, though, type of allocator const allocator_type&, is, const reference allocator_type.
how can use then? 1 thing can const object (or reference one) construct different non-const object it. this, example, builds:
allocator_type(allocator).allocate(n); as sergeya correctly notes in comments, common not construct temporary ad-hoc allocator_type, rather make such member:
allocator_type m_alloc; // should private container( size_type n =0 , const allocator_type& allocator =allocator_type() ) : m_alloc{allocator}{ std::cout << "ctor" << std::endl; m_alloc.allocate(n); };
Comments
Post a Comment