gpt4 book ai didi

c++ - 在 std::containers 中使用 protected 继承的原因

转载 作者:搜寻专家 更新时间:2023-10-31 02:17:22 24 4
gpt4 key购买 nike

GCC implementation of 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 的 protected 继承.我原以为它是私有(private)继承:没有人需要知道 vector<T, A> 根据 vector_base<T, A> 实现,甚至没有派生自 vector<T, A> 的类,因为它不应该被子类化。

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

最佳答案

我怀疑对此有任何合理的解释。这种 protected 继承可以追溯到最初的 SGI STL 实现——可以说是第一个?可能比有人想象的要回来,毕竟会有从 vector 继承的类,可能是库中包含的类。

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

关于c++ - 在 std::containers 中使用 protected 继承的原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35850386/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com