为什么用C ++ 11更改了std :: vector的构造函数接口? [英] Why was the constructor interface of std::vector changed with C++11?

查看:66
本文介绍了为什么用C ++ 11更改了std :: vector的构造函数接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么新标准中删除了默认参数?我经常构造一个矢量变量,如下所示: std :: vector< my_pod_struct> buf(100)。我想我会在C ++ 11编译器中遇到编译器错误。

 显式矢量(size_type count,
const T& value = T(),/ *直到C ++ 11 * /
const Allocator& alloc = Allocator());
vector(size_type count,
const T&值,/ *自C ++ 11起* /
const Allocator& alloc = Allocator());


解决方案

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

现在,当您编写 std :: vector< T> buf(100); ,它将使用另一个构造函数: explicit vector(size_type count); 。这将默认构造一百个 T s。



新的单参数构造函数不需要类型 T 是可复制的。这很重要,因为现在类型可以移动并且不能复制。


Why was the default argument removed with the new standard? Often I constructed a vector variable like this: std::vector<my_pod_struct> buf(100). I guess I would get an compiler error with a C++11 compiler.

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());

解决方案

Before, when you wrote std::vector<T> buf(100); you would get one T default constructed, and then that instance would be copied over to one hundred slots in the vector.

Now, when you write std::vector<T> buf(100);, it will use another constructor: explicit vector( size_type count );. This will default-construct one hundred Ts. It's a slight difference, but an important one.

The new single-argument constructor doesn't require the type T to be copyable. This is important because now types can be movable and not copyable.

这篇关于为什么用C ++ 11更改了std :: vector的构造函数接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆