1

Trying to figure out how to use std :: allocator.

#include <iostream> template <typename T, typename A> struct vector_base { A allocator; T* data; size_t size; size_t space; vector_base(const A &alloc, size_t n) :allocator(alloc), data(alloc.allocate(n)), size(n), space(n) {} ~vector_base() {allocator.deallocate(data, space);} }; int main() { std::allocator<int> my_allocator; vector_base<int, std::allocator<int>> vector(my_allocator, 10); return 0; } 

Error:

error: passing ‘const std::allocator’ as ‘this’ argument discards qualifiers [-fpermissive] :allocator(alloc), data(alloc.allocate(n)), size(n), space(n)

1
  • alloc.allocate(n) you try to call a non-const member function on a const reference Commented May 26, 2019 at 12:27

1 Answer 1

4

alloc is a const&, you're trying to call allocate on it which is a non-const method, that's not allowed.

Call allocate on your initialized member instead:

 vector_base(const A &alloc, size_t n) :allocator(alloc), data(allocator.allocate(n)), size(n), space(n) {} 
Sign up to request clarification or add additional context in comments.

4 Comments

I would suggest not depending on the order in which the data members are declared. I would put data = allocator.allocate(n) in the function body. This way, the code doesn't break if someone moves the declaration of allocator after data.
@L.F. Can't be sure OP runs 11+, but yeah usually you would do that
I think you misunderstood. By “body” I mean the body of the constructor, not in-class member initializer ;-)
wouldn't compiler still move initialization around, because order of initialization is predefined? Though, what may happen, is that someone changes order of fields in class' declaration. THEN it is a problem.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.