Why is this simple assignment undefined behaviour?

喜夏-厌秋 提交于 2019-12-12 10:30:19

问题


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 ();
}

Apparently this is UB because

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?

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 ();

回答1:


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.

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




回答2:


I don't think this is actually undefined behavior although the values in c have unspecified values. That is, the behavior of the program is well defined as long as you don't end up using these unspecified values. If you use them, e.g. in a condition or to print them, the results are not defined. However, I don't think the program is allowed to do anything weird.

With respect to using the default constructor on built-in types, this is guaranteed to yield the type's zero value, i.e. 0 for integers, 0.0 for floating point types, etc. This also extends to the members of types without a constructor. Once there is any constructor you need to take care of constructing your members without a constructor yourself.




回答3:


No. What will happen is most compilers will optimize the setting of the variable out, but those that do not will simply not change the value of x. It is the same as the following code:

int x = 0;
x = 0;

It's not that the second line won't execute, it just won't do anything.



来源:https://stackoverflow.com/questions/9163555/why-is-this-simple-assignment-undefined-behaviour

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!