#include <vector>
#include <iostream>
typedef struct {
unsigned short a;
unsigned short b;
unsigned long c;
}T;
int main(int,char**)
{
std::vector<T> v;
v.resize(256);
std::cout << "a=" << v[0].a << " b=" << v[0].b << " c=" << v[0].c << "\n";
return 0;
}
会是什么v[0].a
(以及 b
和 c
)?
我开始看草稿N4659 Working Draft, Standard for Programming
Language C++搜索 vector::resize
:
26.3.11.3 vector capacity [vector.capacity] (at clause 13)
void resize(size_type sz);
Effects: If
sz < size()
, erases the lastsize() - sz
elements from the sequence. Otherwise, appendssz - size()
default-inserted elements to the sequence.
从那里我需要知道default-inserted 是什么意思然后我得出:
26.2.1 General container requirements [container.requirements.general] (at clause 15.2)
— An element of
X
is default-inserted if it is initialized by evaluation of the expression
allocator_traits<A>::construct(m, p)
where
p
is the address of the uninitialized storage for the element allocated withinX
.
现在,我需要知道里面发生了什么 construct
, 我找到了这个笔记
26.2.1 General container requirements [container.requirements.general] (at the end of clause 15)
[ Note: A container calls
allocator_traits<A>::construct(m, p, args)
to construct an element atp
usingargs
, withm == get_allocator()
. The default construct in allocator will call::new((void*)p) T(args)
, but specialized allocators may choose a different definition. — end note ]
我还好吗?我的代码段是否使用了专门的分配器?我认为最后我的代码片段会调用 new T()
现在,根据 https://stackoverflow.com/a/8280207我想a
, b
和 c
, 将是 0
,我说得对吗?
最佳答案
是的,你是对的。您没有使用专门的(定制的)分配器。最后元素得到 value initialized .来自 DefaultInsertable :
By default, this will call placement-new, as by
::new((void*)p) T()
(that is, value-initialize the object pointed to byp
).
作为 value initialization 的结果, T
的所有成员都将被零初始化。
(强调我的)
if T is a class type with a default constructor that is neither user-provided nor deleted (that is, it may be a class with an implicitly-defined or defaulted default constructor), the object is zero-initialized and then it is default-initialized if it has a non-trivial default constructor;
关于c++ - std::vector of struct:调整 vector 大小后结构成员的初始值是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55377407/