gpt4 book ai didi

c++ - std::vector of struct:调整 vector 大小后结构成员的初始值是多少?

转载 作者:太空狗 更新时间:2023-10-29 19:42:58 30 4
gpt4 key购买 nike

#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 (以及 bc )?

我开始看草稿N4659 Working Draft, Standard for ProgrammingLanguage 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 last size() - sz elements from the sequence. Otherwise, appends sz - 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 within X.

现在,我需要知道里面发生了什么 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 at p using args, with m == 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 , bc , 将是 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 by p).

作为 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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com