简体   繁体   中英

Why is allocator const in 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?

Allocators are supposed to have value semantics, which means the vector stores it by value (notice that get_allocator() returns by value). So the constructor can easily take the allocator by const reference and just copy it.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM