Which allocator does std::vector’s copy constructor use to allocate memory?

  allocator, c++

I have a custom allocator template MyAllocator<T>. I am attempting to create a class template that essentially boils down to the following:

template<typename T>
class MyClass<T> {
    std::vector<T, MyAllocator<T>> &data;
public:
    MyClass(std::vector<T, MyAllocator<T>> &data) : data(data) {}
    MyClass(std::vector<T> &data) : data(data) {}

My intention is to avoid copying data when its memory allocation was dictated by MyAllocator<T>. I know that this can be hairy in some contexts, but this class is a short-lived utility wrapper, and this is a performance-critical application.

The part that confuses me, however, is the member initializer list of the second constructor. After looking closely at the documentation, I can’t seem to explain why this operation is type-safe. It is my understanding that data(data) will look for the constructor std::vector<T, MyAllocator<T>>::vector(std::vector<T, std::allocator<T>>) (or a pass-by-reference variant). This constructor doesn’t seem to exist, yet I have not encountered any compile-time type errors.

At first I thought it was because the data member variable is a reference, but changing it to a value did not create any type errors. MyAllocator is not a subclass of std::allocator, so I don’t see how an implicit cast could be responsible for this behavior either.

What am I missing? And if this is indeed legal code, does the second constructor create a new memory allocation with MyAllocator like I’m hoping it does?

Source: Windows Questions C++

LEAVE A COMMENT