为什么std::vector的构造函数接口在C++11中发生了变化

Why was the constructor interface of std::vector changed with C++11?

本文关键字:C++11 发生了 变化 构造函数 std vector 为什么 接口      更新时间:2023-10-16

为什么新标准删除了默认参数?我经常构造这样一个向量变量:std::vector<my_pod_struct> buf(100)。我想用C++11编译器会出现编译器错误。

explicit vector( size_type count,
                 const T& value = T(),                   /* until C++11 */
                 const Allocator& alloc = Allocator());
         vector( size_type count,
                 const T& value,                         /* since C++11 */
                 const Allocator& alloc = Allocator());

以前,当您编写std::vector<T> buf(100);时,您将获得一个默认构造的T,然后该实例将被复制到向量中的一百个插槽中。

现在,当您编写std::vector<T> buf(100);时,它将使用另一个构造函数:explicit vector( size_type count );。这将默认构造一百个T s。这是一个微小的区别,但却是一个重要的区别。

新的单参数构造函数不要求类型T是可复制的。这一点很重要,因为现在类型可以移动而不可复制。

您不会,现在有单独的构造函数用于您的用例:

explicit vector(size_type n);