gpt4 book ai didi

c++ - 初始化 vector 中的指针

转载 作者:太空宇宙 更新时间:2023-11-04 15:39:31 25 4
gpt4 key购买 nike

我正在尝试将 vector 中的所有指针初始化为 NULL。基于线程: initialize vector of pointers (automatically)How to initialize a vector of pointers

我可以只使用 vector 构造函数来实现我想要的。我的问题是:初始化 NULL 指针是标准行为吗?或者 vector 中的指针在某些编译器上可能不是 NULL?如果初始化为NULL是标准的,谁能告诉我在哪一章和哪一节可以找到c++标准的相关信息?

谢谢,

最佳答案

我假设你的意思是这样的:

std::vector<MyClass*> v(10);

是的, vector 是用空指针初始化的。逐章引用标准有点牵强……

C++14 §23.3.6.2 “` vector 构造函数、复制和赋值”:

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.

§23.2.1“一般容器要求”¶13:

T is DefaultInsertable into X means that the following expression is well-formed:

allocator_traits<A>::construct(m, p)

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

§20.7.8.2“分配器特征成员函数”¶5:

template <class T, class... Args>
static void construct(Alloc& a, T* p, Args&&... args);

Effects: calls a.construct(p, std::forward<Args>(args)...) if that call is well-formed; otherwise, invokes ::new (static_cast<void*>(p)) T(std::forward<Args>(args)...).

§20.7.9.1 “[默认] allocator成员”¶12:

template <class U, class... Args>
void construct(U* p, Args&&... args);

Effects: ::new((void *)p) U(std::forward<Args>(args)...)

回到 §23.2.1 ¶13,看到 args是空的。因此……

§8.5 “初始化器”:

An object whose initializer is an empty set of parentheses, i.e., (), shall be value-initialized.

相同部分:

To value-initialize an object of type T means: … otherwise, the object is zero-initialized.

相同部分:

To zero-initialize an object or reference of type T means: … if T is a scalar type (3.9), the object is initialized to the value obtained by converting the integer literal 0 (zero) to T;106

脚注 106:

As specified in 4.10, converting an integer literal whose value is 0 to a pointer type results in a null pointer value.

关于c++ - 初始化 vector 中的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25903968/

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