Can uninitialized data be copied if it is not used / installed later?

Is the following code safe if I don't read any elements of a struct array without setting it with a real value in the first place? Thanks.

const int data_size = 5; struct Testing { int data[data_size]; Testing(const int data[data_size]) { std::copy(data, data + data_size, this->data); } }; int main() { int data[data_size]; data[2] = 57; Testing t(data); t.data[1] = 93; } 
+6
source share
1 answer

std::copy defined as executing *(result + n) = *(first + n) for each element in the sequence (ยง 25.3.1). The value indicated by *(first + n) is an lvalue expression (ยง5.3.1 / 1), in your case related to an uninitialized value. Since the assignment operator expects prvalue as its right operand (this is not specified ), this will result in an lvalue-to-rvalue conversion. Converting an Lvalue-to-rvalue to an expression relating to an uninitialized value is undefined behavior (ยง 4.1):

If the object to which the glvalue belongs is not an object of type T and is not an object of a type derived from T, or if the object is not initialized, the program that requires this conversion has undefined behavior.

So your code has undefined behavior. Of course, the solution should initialize the elements of the array (possibly using int data[data_size] = {}; ).

+9
source

All Articles