6

下面的代码是否安全,只要我不读取结构数组的任何元素而不首先将其设置为实际值?谢谢。

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;
}
4

1 回答 1

9

std::copy is defined as doing *(result + n) = *(first + n) for each element in the sequence (§25.3.1). The value given by *(first + n) is an lvalue expression (§5.3.1/1), in your case referring to an uninitialized value. Since the assignment operator expects a prvalue as it's right operand (this is ill-specified), this will result in lvalue-to-rvalue conversion. Lvalue-to-rvalue conversion on an expression referring to an uninitialized value is undefined behaviour (§4.1):

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

So your code has undefined behaviour. The solution is of course to initialize the elements of the array (perhaps with int data[data_size] = {};).

于 2013-03-05T18:49:14.840 回答