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

标签 c++ struct language-lawyer standards default-constructor

#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 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 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/

相关文章:

c++ - C 到 C++ : Converting structs to classes

c++ - ImageMagick 与 Cairo 在 vector 图形光栅化方面的对比

c++ - 我可以在 OpenGL (C++) 的缓冲区中混合数据类型吗?

c++ - C++ 中基于 ifdef 的继承问题

c++ - 什么时候允许推导 initializer_list?

c++ - 以下使用 const_cast 是未定义的行为吗?

c++ - 在 gcc 中意外调用了 const 重载。编译器错误或兼容性修复?

c++ - 重构期间结构的聚合初始化是否安全?

sizeof() 是否可以为同一类型返回不同的值?

c++ - 释放包含字符串变量的结构