为什么这个简单的赋值是未定义的行为? [英] Why is this simple assignment undefined behaviour?

查看:39
本文介绍了为什么这个简单的赋值是未定义的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在刷新我对值初始化与默认初始化的理解,并且遇到了这个:

I was refreshing my understanding of value-initialisation versus default-initialisation, and came across this:

struct C {
    int x;
    int y;
    C () { }
};

int main () {
    C c = C ();
}

显然这是 UB 因为

在 C() 的情况下,有一个构造函数能够初始化 x 和 y 成员,因此不会发生初始化.因此,尝试将 C() 复制到 c 会导致未定义的行为.

In the case of C(), there is a constructor that is capable of initializing the x and y members, so no initialization takes place. Attempting to copy C() to c therefore results in undefined behavior.

我想我明白为什么,但我不确定.有人能详细说明一下吗?

I think I understand why, but I'm not certain. Can someone please elaborate?

这是否意味着这也是 UB?

Does that mean this is also UB?

int x; x = x;

顺便说一下,关于值的初始化,以下保证为零吗?

Incidentally, with regards to value initialisation, is the following guaranteed to be zero?

int x = int ();

推荐答案

你的第一个例子有未定义的行为,因为默认的编译器生成的拷贝构造函数会做一个成员拷贝,ints 可能有捕获值,并读取捕获值以复制它可能会导致程序崩溃.

Your first example has undefined behavior because the default, compiler generated copy constructor will do a memberwise copy, ints may have trapping values, and reading a trapping value to copy it may cause the program to crash.

在实践中,我无法想象这真的会崩溃;编译器几乎肯定会优化副本,即使没有,它可能会使用一些特殊的按位复制检查捕获值.(在 C++ 中,保证您能够复制字节.)

In practice, I can't imagine this ever actually crashing; the compiler will almost certainly optimize the copy out, and even if it didn't, it would likely use some special bitwise copy which would copy without checking for trapping values. (In C++, you are guaranteed to be able to copy bytes.)

对于第二种情况,同样是未定义的行为.虽然在这种情况下,你有赋值而不是复制构造,编译器是不太可能优化它.(你的第一个没有分配例如,仅复制构造.)

For the second case, again, undefined behavior. Although in this case, you have assignment rather than copy construction, and the compiler is less likely to optimize it away. (There is no assignment in your first example, only copy construction.)

对于第三个,是的.带有空括号的初始化程序(并且没有用户定义的默认初始值设定项覆盖它)首先执行零初始化(与具有静态生命周期的变量完全一样).

For the third, yes. An initializer with an empty parenthese (and no user defined default initializer to override it) first performs zero initialization (exactly as occurs for variables with static lifetime).

这篇关于为什么这个简单的赋值是未定义的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆