Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is allocator const in vector?

Tags:

c++

vector

vector has this in every type of constructor

const allocator_type& alloc = allocator_type()

Why is it const? I can't see how that'd be useful. I can see passing in an allocator so multiple vectors can share the same pool but be grouped away from another bunch of vectors. However with const wouldnt that mean they'd only copy the instance data? copying a pool or whatever it is doesn't seem to be useful.

Why is it const?

like image 572
user2814152 Avatar asked Sep 25 '13 09:09

user2814152


People also ask

What does const vector mean?

A constant vector is one which does not change with time (or any other variable). For example, the origin (0,0,0) is constant, and the point (34,2,2234) is constant.

What is a std :: vector?

1) std::vector is a sequence container that encapsulates dynamic size arrays. 2) std::pmr::vector is an alias template that uses a polymorphic allocator. The elements are stored contiguously, which means that elements can be accessed not only through iterators, but also using offsets to regular pointers to elements.


1 Answers

Actually, passing the allocator as const reference and copying it inside the container simplifies things. Otherwise if only a reference was passed in, you would have to ensure that the allocator is not destroyed before the container. You just need to share the allocator state between its copies. You can do that simply by holding the pool in a shared_ptr.

like image 124
Juraj Blaho Avatar answered Oct 06 '22 01:10

Juraj Blaho