默认插入向量不是默认初始化? [英] Default-inserting into a vector isn't default initialization?

查看:125
本文介绍了默认插入向量不是默认初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std :: vector 构造函数之一被规定为,强调我的:

One of the std::vector constructors is stipulated as, emphasis mine:


显式向量(size_type n,const Allocator& = Allocator());

code>使用指定的分配器使用 n 默认插入的元素。 b 需要: T 应为 DefaultInsertable into * this。

explicit vector(size_type n, const Allocator& = Allocator());
Effects: Constructs a vector with n default-inserted elements using the specified allocator.
Requires: T shall be DefaultInsertable into *this.
Complexity: Linear in n.

默认插入以任何方式与默认初始化相关?对此代码:

Is default-insertion in any way related to default initialization? On this code:

std::vector<char> v(66000);

gcc 5.2优化产生:

gcc 5.2 optimized produces:

  400d18:   bf d0 01 01 00          mov    $0x101d0,%edi
  400d1d:   48 83 c5 01             add    $0x1,%rbp
  400d21:   e8 1a fd ff ff          callq  400a40 <operator new(unsigned long)@plt>
  400d26:   31 f6                   xor    %esi,%esi
  400d28:   48 89 c3                mov    %rax,%rbx
  400d2b:   ba d0 01 01 00          mov    $0x101d0,%edx
  400d30:   48 89 c7                mov    %rax,%rdi
  400d33:   e8 38 fc ff ff          callq  400970 <memset@plt>

memset ?你在这里做什么?我认为这应该简单地做相当于 new char [66000] ...那就是没有初始化。 clang 3.7还会发出一个 memset

memset? What are you doing here? I thought this should simply do the equivalent of new char[66000]... that is, no initialization. clang 3.7 also emits a memset.

为什么在这里有一个 memset ?这是正确的标准吗?毕竟,如果我想要66000个价值初始化的字符,我已经有这个构造函数:

Why is there a memset here? Is this correct with respect to the standard? After all, if I wanted 66000 value-initialized chars I already have this constructor:

std::vector<char> v(66000, '\0');


推荐答案

请参见23.2.1:


如果通过评估表达式初始化X的元素, allocator_traits< A> :: construct(m,p)

allocator_traits< A> :: construct 将调用 a.construct(p,std :: forward< Args>(args)...)。反过来,它调用 :: new((void *)p)U(std :: forward< Args>(args)...) new(),它会执行值初始化。

Than, allocator_traits<A>::construct will call a.construct(p, std::forward<Args>(args)...). Which, in turn, calls ::new((void *)p) U(std::forward<Args>(args)...), which in effect calls new(), which does value-initialization.

memset()是合适的。

缺少自定义分配器, std :: vector 不允许一个选项访问未初始化的存储。在向量中合法的每个对象都是值初始化的。

Absent custom allocators, std::vector does not allow one an option to access uninitialized storage. Every object which is legitimately in vector was value-initialized.

这篇关于默认插入向量不是默认初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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