受保护变量的命名和标准

Protected variables naming and the standard

本文关键字:标准 变量 受保护      更新时间:2023-10-16

我偶然看到一篇介绍可迭代队列的文章。OP在实现中使用了来自std::queue的受保护变量c

这是完全有效的吗?这个变量是否在所有实现中都具有相同的名称?也就是说,标准是否明确规定这个变量必须命名为c ?

为供参考,这里列出了std::queue的确切定义。所以在回答

换句话说,标准是否明确规定这个变量必须命名为c ?

是的,在这种情况下(对于其他容器适配器也是类似的);

template <class T, class Container = deque<T>>
  class queue {
  protected:
    Container c;
    // ...
  };

然而,一般来说,受保护的和私有的名字和成员的名字是不标准化的,因为类型并不是都被构建为派生的,并且实现是一个实现细节(并且不构成公共API的一部分);例如,std::vector没有列出任何受保护的名称。

一些std容器和类确实定义了protected成员的名称,特别是想到了iostreams库——基本上是打算从这些类型派生出来的。


作为后续- 是否所有的编译器/库都使用c ?看起来,至少主流软件(libstdc++、libc++和MSVC)是这样做的。libstdc++很有趣,因为它在变量上包含了以下注释;

/**
 *  'c' is the underlying container.  Maintainers wondering why
 *  this isn't uglified as per style guidelines should note that
 *  this name is specified in the standard, [23.2.3.1].  (Why?
 *  Presumably for the same reason that it's protected instead
 *  of private: to allow derivation.  But none of the other
 *  containers allow for derivation.  Odd.)
 */
_Sequence c;