std::vector类似于以下代码:
#include <memory>
template<
typename T,
typename Allocator
> struct vector_base {
using T_alloc = typename std::allocator_traits<Allocator>::template rebind_alloc<T>;
using pointer = typename std::allocator_traits<T_alloc>::pointer;
struct vector_imp
: public T_alloc {
pointer m_start;
pointer m_finish;
pointer m_end_of_storage;
vector_imp()
: m_start(), m_finish(), m_end_of_storage() { }
vector_imp(const T_alloc& a)
: T_alloc(a), m_start(), m_finish(), m_end_of_storage() { }
// move constructor and swap defined here...
};
vector_imp m_imp; // the sole member of vector_base
// methods for allocating/deallocating and creating storage;
// destructor.
};
// this class is the "actual" std::vector which you instantiate via
// std::vector<T> x;
template<
typename T,
typename Allocator = std::allocator<T>
> class vector
: protected vector_base<T, Allocator> {
// all the interface is implemented in terms of calls to vector_imp;
// this class has no members (except, of course, from the member of
// vector_base<T, Allocator>)
};本质上,API是根据基类和实现类实现的。实现类包含三个不可或缺的成员:存储开始、数据结束和存储结束。
我理解为什么vector_imp来自T_alloc:空基优化将确保无状态分配器不会占用std::vector中的任何空间。
但是,我不明白为什么vector使用vector_base的受保护继承。我原以为它是私有继承:没有人需要知道vector<T, A>是按照vector_base<T, A>实现的,甚至不是从vector<T, A>派生的类,因为它不打算被子类化。
你能解释一下这个设计的选择吗?
发布于 2016-03-07 18:15:56
我怀疑对此是否有任何合理的解释。这种受保护的继承可以追溯到最初的SGI STL实现--可以说是第一个?可能比有人想象的还早,毕竟会有从向量中继承的类,很可能是包含在库中的类。
它没有发生(据我所知,至少在stdcxx标准库实现中没有向量的后代),但可能没有人对更改这个继承说明符感兴趣。
https://stackoverflow.com/questions/35850386
复制相似问题