Michael Chourdakis
Michael Chourdakis

Reputation: 11158

std::vector against std::vector with custom allocator

Well I'm using my own allocator for a vector that has fast run-time requirements to avoid calling new/delete. The problem is now that code like this is not compiling:

std::vector<char> x(1000);
std::vector<char,myalloc<char>> y(1000);
x = y;

This obviously occurs because the implementation of the std::vector's allocator is compile-time and changes the type. But code like the above should be allocator-independent.

For POD I can do memcpy of course, but is there any other method? I'm really close to implementing my own vector that would use a custom allocator dynamically, specified at run time and get rid of std::vector.

Upvotes: 1

Views: 1562

Answers (1)

L. F.
L. F.

Reputation: 20579

But code like the above should be allocator-independent.

Assigning the elements should indeed be allocator-independent. But the copy assignment operator of std::vector does more than just assign elements — it also takes care of allocators. So it should not be allocator-independent.

std::vector does provide an interface for assigning elements only: the assign member function. It can be used like this:

x.assign(y.begin(), y.end());

Since C++17, polymorphic allocators allow allocator-aware containers to have type-erased allocator support, so you can consistently use std::pmr::vector<char>, but it has some problems you need to consider — overhead of type erasure, different allocator propagation semantics, different interface, etc.

Upvotes: 3

Related Questions