Search code examples
c++arrayscopy-constructorcopy-assignment

Default copy behavior with array of objects


If I have a class with an array as a member:

class A
{
    Object array[SIZE];
};

And I copy an instance of it:

A a;
A b = a;
A c;
c = a;

will array be memcpy-ed byte-by-byte or Object::operator= copied element-by-element?


Solution

  • Arrays in C++ are well behaved for all first class objects, including user defined types (no matter whether they are POD/non-trivially constructible).

    #include <cstdio>
    
    struct Object
    {
        Object()              { puts("Object");  } 
        Object(Object const&) { puts("copy");    } 
       ~Object()              { puts("~Object"); } 
    };
    
    struct A
    {
        Object array[4];
    };
    
    int main()
    {
        A a;
        A b = a;
    }
    

    Output (see also http://liveworkspace.org/code/40380f1617699ae6967f0107bf080026):

    Object
    Object
    Object
    Object
    copy
    copy
    copy
    copy
    ~Object
    ~Object
    ~Object
    ~Object
    ~Object
    ~Object
    ~Object
    ~Object