首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在std::容器中使用受保护继承的原因

在std::容器中使用受保护继承的原因
EN

Stack Overflow用户
提问于 2016-03-07 17:44:00
回答 1查看 93关注 0票数 2

std::vector类似于以下代码:

代码语言:javascript
复制
#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>派生的类,因为它不打算被子类化。

你能解释一下这个设计的选择吗?

EN

回答 1

Stack Overflow用户

发布于 2016-03-07 18:15:56

我怀疑对此是否有任何合理的解释。这种受保护的继承可以追溯到最初的SGI STL实现--可以说是第一个?可能比有人想象的还早,毕竟会有从向量中继承的类,很可能是包含在库中的类。

它没有发生(据我所知,至少在stdcxx标准库实现中没有向量的后代),但可能没有人对更改这个继承说明符感兴趣。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35850386

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档