Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 983
John Avatar asked Oct 10 '12 20:10

John


1 Answers

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
like image 185
sehe Avatar answered Nov 10 '22 04:11

sehe