Question

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 ();
Was it helpful?

Solution

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

OTHER TIPS

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top