1

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.

4
  • Can you use assign? en.cppreference.com/w/cpp/container/vector/assign Commented Mar 2, 2020 at 7:14
  • @jtbandes yes but this would require a big edit in the code. Commented Mar 2, 2020 at 7:16
  • 1
    x.assign(y.begin(), y.end()) or (C++11) x.assign(std::begin(y), std::end(y)) should do it. A vector's operator=() doesn't have overloads for that to work, regardless of what you think "should" be the case. If you really want a type which works that way, create a simple struct/class type - templated if required - that contains a vector (with whatever element type and allocator you use) and ensure its operator=() works as required. Commented Mar 2, 2020 at 7:30
  • If I'm not mistaken you can use std::pmr::vector instead of just std::vector everywhere and everything should "just work". Commented Mar 2, 2020 at 7:37

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Good concise answer. I just want to add begin() and end() can also be used right in the ctor like std::vector<whatever> y(x.begin(), x.end());
@nada Yeah. In fact, they can be used in any context where a range denoted by a pair of iterators is needed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.