问题描述
我正在刷新我对值初始化与默认初始化的理解,并且遇到了这个:
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 会导致未定义的行为.
我想我明白为什么,但我不确定.有人能详细说明一下吗?
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 ();
推荐答案
你的第一个例子有未定义的行为,因为默认的编译器生成的拷贝构造函数会做一个成员拷贝,int
s 可能有捕获值,并读取捕获值以复制它可能会导致程序崩溃.
Your first example has undefined behavior because the default, compilergenerated copy constructor will do a memberwise copy, int
s may havetrapping values, and reading a trapping value to copy it may cause theprogram to crash.
在实践中,我无法想象这真的会崩溃;编译器几乎肯定会优化副本,即使没有,它可能会使用一些特殊的按位复制检查捕获值.(在 C++ 中,保证您能够复制字节.)
In practice, I can't imagine this ever actually crashing; the compilerwill almost certainly optimize the copy out, and even if it didn't, itwould likely use some special bitwise copy which would copy withoutchecking for trapping values. (In C++, you are guaranteed to be able tocopy bytes.)
对于第二种情况,同样是未定义的行为.虽然在这种情况下,你有赋值而不是复制构造,编译器是不太可能优化它.(你的第一个没有分配例如,仅复制构造.)
For the second case, again, undefined behavior. Although in this case,you have assignment rather than copy construction, and the compiler isless likely to optimize it away. (There is no assignment in your firstexample, only copy construction.)
对于第三个,是的.带有空括号的初始化程序(并且没有用户定义的默认初始值设定项覆盖它)首先执行零初始化(与具有静态生命周期的变量完全一样).
For the third, yes. An initializer with an empty parenthese (and nouser defined default initializer to override it) first performs zeroinitialization (exactly as occurs for variables with static lifetime).
这篇关于为什么这个简单的赋值是未定义的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!