c++ - 是否为 initializer_list 提供一个私有(private)构造函数?

标签 c++ c++11 language-lawyer c++-standard-library

此标准草案显示了 initializer_list 的概要.它没有私有(private)构造函数。

http://i.stack.imgur.com/5bc61.png

但是我看过的两个标准库实现,libstdc++ 和 libc++,都提供私有(private)构造函数:

  // The compiler can call a private constructor.
  constexpr initializer_list(const_iterator __a, size_type __l)
  : _M_array(__a), _M_len(__l) { }

_LIBCPP_ALWAYS_INLINE
_LIBCPP_CONSTEXPR_AFTER_CXX11
initializer_list(const _Ep* __b, size_t __s) _NOEXCEPT
    : __begin_(__b),
      __size_(__s)
    {}

我相信这个私有(private)构造函数是“隐含”的部分源于§8.5.4/5:

An object of type std::initializer_list<E> is constructed from an initializer list as if the implementation allocated a temporary array of N elements of type const E, where N is the number of elements in the initializer list. Each element of that array is copy-initialized with the corresponding element of the initializer list, and the std::initializer_list<E> object is constructed to refer to that array.

所以我的问题是:

  • 大纲是否未详细说明?

  • 库是否需要私有(private)构造函数?它做了哪些编译器做不到的事情?

最佳答案

Is the synopsis under-specified?

不,它记录了 initializer_list 的面向用户的位类模板,您实际上可以在代码中使用的部分。根据概要,模板仅包含一个默认构造函数,允许您创建空 initializer_list s,这显然不是很有用。然而,initializer_list<T>是一种依赖于编译器执行的某些魔法 的类型。神奇的是,我指的是您引用的§8.5.4/5。这使得下面的语句是合法的并且可以编译。

std::initializer_list<int> numbers{1, 2, 3, 4}; // no such constructor in the synopsis

这里,如 §8.5.4/5 中所述,编译器将创建一个包含四个整数的数组,然后初始化 initializer_list<int>带有一对指针(第一个元素和结束元素之后的一个)或一个指针和长度(libstdc++ 和 libc++ 似乎都这样做)的实例。

创建实例后,您的代码就可以访问概要中列出的所有成员函数。

Does the library need a private constructor? What does it do that the compiler can't?

正如 libstdc++ 私有(private)构造函数定义上方的注释所暗示的那样,编译器能够发出绕过正常访问控制的代码,所以不,我认为拥有该构造函数不是必需的。编译器可以使用默认构造函数构造一个空的 initializer_list实例,然后将适当的值分配给私有(private)数据成员(这些也没有在概要中列出,但是是必需的)。

但是,当私有(private)构造函数提供编译器可以调用的干净接口(interface)时,为什么还要为这种笨拙而烦恼呢?

关于c++ - 是否为 initializer_list 提供一个私有(private)构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29200036/

相关文章:

c++11 - 为什么 'scientific' 改变了 'precision' 的含义?

c++ - 我怎样才能列出初始化我自己的类(class)?

c++ - 为什么共享锁只能持有一把可升级锁

c++ - 多重继承情况下的销毁顺序

c++ - 取消引用无效指针但不使用结果是 C++ 中的未定义行为吗?

c++ - glfwInit() 失败。我应该怎么办?

c++ - 链表节点插入

c++ - OpenAL:定位 freealut 或修复此代码

c++ - 使用较小的默认对齐方式重载 operator new

c++ - 在可能不完整的类型上进行可选的安全检查