c++ - C ++如何在容器类复制构造函数中复制分配器对象
问题描述
我正在实现一个环形缓冲区容器类:
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_)) {
}
See also: AllocatorAwareContainer
推荐阅读
- node.js - TypeError:Model.find 不是函数
- python - python脚本未编码为utf-8
- angular - 将匿名用户转换为注册用户
- shell - 在 unix 中删除 .csv 文件中的多列
- angular - Nginx 和 SPA (Angular)
- ios - iOS 设备上的 Expo.io 离线测试
- objective-c - (Mac) 创建键盘事件会导致内存泄漏
- lua - 如何编写 Roblox 脚本来在玩家死后保存他们的背包和入门装备?
- javascript - 如何在 Vis 中的节点顶部绘制边缘?
- javascript - Yii2 的 jQuery 倒计时小部件的俄语复数