Default-inserting into a vector isn't default initialization?

匿名 (未验证) 提交于 2019-12-03 03:10:03

问题:

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

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 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? 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.

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

回答1:

This is correct behaviour. See 23.2.1:

An element of X is default-inserted if it is initialized by evaluation of the expression allocator_traits<A>::construct(m, p)

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.

Conclusion:

memset() is appropriate.

Conclusion #2

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!