1

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?

4
  • 4
    Because structs, like classes, do have a default operator= that copies each member. Commented Dec 28, 2015 at 10:25
  • 1
    @DavidSchwartz yes? This is what I wrote, the default operator= is invoked, which will in turn apply operator= on every member, my question is: how does this work given arrays don't have operator= (i.e. can't be copied) Commented Dec 28, 2015 at 10:59
  • 1
    The default operator= copies each member. It doesn't necessarily call operator= on them unless that's the appropriate way to copy them. Why should a struct with int r[2]; copy differently from a struct with int r1, r2;? Commented Dec 28, 2015 at 11:00
  • 1
    @DavidSchwartz: I see, thanks for the clarification! Commented Dec 28, 2015 at 11:03

1 Answer 1

6

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{};
Sign up to request clarification or add additional context in comments.

2 Comments

So the standard specifies the meaning of "copying" an array. I guess the only reason why operator= isn't defined for an array is that it would cause a mess when arrays decay into pointers?
@qdii It is a mess inherited from C. It would be hard to reconcile copy of arrays with pointer decay (and particularly array function parameter adjustment), although I don't see obvious problems with assignment. But it is the way it is and it can't be changed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.