gpt4 book ai didi

c++ - 包含未初始化值的对象 vector

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:30:57 25 4
gpt4 key购买 nike

此代码是否会导致未定义的行为:

#include <vector>

struct S
{
S() {}

int x;
};

int main()
{
std::vector<S> vec(5, S());
}

S()默认初始化一个自动对象,它的内容不会先归零,所以 x将是不确定的。然后将包含不确定值的对象复制到每个 vector 位置。

动机:我们可能希望它的行为与 std::vector<S> vec(5); 相同这不是 UB (C++11 起),所以这是一个很容易不小心犯的错误。

正如 Praetorian 在 C++11 之前的评论中提到的 std::vector<S> vec(5);可以自由地进行 5 次默认初始化,或者对部分或全部项目使用复制构造函数。

最佳答案

因此考虑到 OP 的以下评论:

vector vec(5); is not UB (is it?) and we tend to think that (5) and (5, S()) ought to do the same thing. I could see this mistake being made by accident quite easily.

问题归结为如果:

vector<S> vec(5);

定义明确那么为什么是:

std::vector<S> vec(5, S());

未定义的行为?

如果我们转到 std::vector::vector 的 cppreference 部分我们可以在第一种情况下看到它(自 C++11 )(强调我的):

Constructs the container with count default-inserted instances of T. No copies are made.

在第二种情况下:

Constructs the container with count copies of elements with value value.

第一种情况将默认构造元素并且不进行任何复制,而在第二种情况下将进行复制,因此我们最终将 x 复制到每个元素。由于 S 的默认构造函数不初始化 x,它将有一个不确定的值,因此我们在生成 后有未定义的行为不确定值 调用未定义的行为。

自 C++14 部分 8.5 段落 12 说:

If an indeterminate value is produced by an evaluation, the behavior is undefined except in the following cases

但在 unsigned char 的情况下有一些异常(exception),它不适用于这种情况。

我们知道 x 在同一段中有一个不确定的值,它说:

When storage for an object with automatic or dynamic storage duration is obtained, the object has an indeterminate value, and if no initialization is performed for the object, that object retains an indeterminate value until that value is replaced

关于c++ - 包含未初始化值的对象 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27699118/

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