C++ 如何在容器中复制分配器对象 class 复制构造函数

C++ How to copy the allocator object in a container class copy constructor

我正在实现一个环形缓冲区容器class:

template <class T, class A = std::allocator<T>>
class ring {
private:
    size_type cap_;  // the capacity of the array
    alloc_type alloc_;  // the allocator
    pointer array_;
    ...  
public:
    ring(size_type n, const alloc_type &a = alloc_type()) : cap_{n}, alloc_{a}, array_{alloc_.allocate((size_t)cap_)}, ... {
       memset(array_, 0, (size_t)cap_ * sizeof(T));
    }
    ...
};

(我没有在这里显示 typedef,但它们很明显。)

我不确定如何编写(深)复制构造函数以便它正确处理分配器,但我想复制必须有自己的分配器(相同类型),然后我会遍历原始分配的数组并逐个元素复制。

会是这样吗?:

ring(const self_type& r) : cap_{r.cap_}, ... {
    alloc_ = ???  // not sure what to do here
    array_ = alloc_.allocate((size_t)cap_);
    for (size_type i{}; i < r.size(); ++i) {   
        alloc_.construct(array_[i], r.array_[i]);
    }
}
ring(const self_type& r)
  : alloc_(std::allocator_traits<alloc_type>::
        select_on_container_copy_construction(r.alloc_)) {
}

另请参阅:AllocatorAwareContainer