Search code examples
c++arraysassignment-operator

Calling assignment operator on an array


I wonder how this code could work:

struct my_array
{
    int r[1000];
};

int main()
{
    my_array foo, bar;
    foo = bar;
}

Because the foo = bar call will invoke the constructor-provided operator= for the class, which will lazily apply it on every members. But arrays don't have an implementation for operator=, proof is, this code fails to compile:

int main()
{
    int a[1000], b[1000];
    a = b;
}

So how come my first code compiles?


Solution

  • So how come my first code compiles?

    The language specification says it has to work, and the compiler implements that behaviour.

    The default assignment semantics are specified in clause 28 of § 12.8 [class.copy]. Specifically, the object's data members are assigned one by one. In the case of an array, this the array's elements are assigned one by one.

    The implicitly-defined copy/move assignment operator for a non-union class X performs memberwise copy- /move assignment of its subobjects. ...

    and

    — if the subobject is an array, each element is assigned, in the manner appropriate to the element type;

    (emphasis mine)


    Note that in your particular example, the first code sample invokes undefined behaviour because the elements of bar are uninitialized at the moment you read from them here:

    foo = bar; // UB: bar.r uninitialized
    

    You can fix that by suitable initializing bar:

    my_array foo;
    my_array bar{};