加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 新分配的std :: vector元素是否初始化为0?

发布时间:2020-12-16 10:43:48 所属栏目:百科 来源:网络整理
导读:让我们说,我们使用std :: vector int或std :: vector long.随着向量的大小增加,默认情况下新分配的元素是否会被初始化为0,或者程序员是否需要显式地将它们归零? 解决方法 新元素是价值初始化的: [C++11: 23.3.6.3/9]: void resize(size_type sz); Effects:
让我们说,我们使用std :: vector< int>或std :: vector< long>.随着向量的大小增加,默认情况下新分配的元素是否会被初始化为0,或者程序员是否需要显式地将它们归零?

解决方法

新元素是价值初始化的:

[C++11: 23.3.6.3/9]: void resize(size_type sz);

Effects: If sz <= size(),equivalent to erase(begin() + sz,end());. If size() < sz,appends sz - size() value-initialized elements to the sequence.

对于int和long,这意味着0:

[C++11: 8.5/7]: To value-initialize an object of type T means:

  • if T is a (possibly cv-qualified) class type (Clause 9) with a user-provided constructor (12.1),then the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);
  • if T is a (possibly cv-qualified) non-union class type without a user-provided constructor,then the object is zero-initialized and,if T’s implicitly-declared default constructor is non-trivial,that constructor is called.
  • if T is an array type,then each element is value-initialized;
  • otherwise,the object is zero-initialized.

An object that is value-initialized is deemed to be constructed and thus subject to provisions of this International Standard applying to “constructed” objects,objects “for which the constructor has completed,” etc.,even if no constructor is invoked for the object’s initialization.

但请注意,这并不是在向量的末尾讨论“保留”空间.此空间不包含任何有效元素,零初始化或其他.此答案和标准措辞仅讨论在执行调整大小时未获得新元素的显式值时获得的元素.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读