5

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?

David G
  • 94,763
  • 41
  • 167
  • 253
John
  • 7,301
  • 2
  • 16
  • 23

1 Answers1

8

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
sehe
  • 374,641
  • 47
  • 450
  • 633
  • The compiler may optimize a POD copy by replacing it with a memcpy or equivalent, but it's not required to. – Mark Ransom Oct 10 '12 at 20:33
  • 1
    I'm not worried about optimizations if they end up with equivalent behavior. I want to make sure that my container class will behave well with the default copy constructor and assignment operator, regardless of the contained type, before I decide it's O.K. to not implement them myself. – John Oct 10 '12 at 20:42
  • 1
    @John short version: yes you're fine: array elements are also first class objects. This is C++. Even `goto` is safe with constructors/destructors and exceptions etc. You have to try hard to shoot yourself in the foot (but when you do...) – sehe Oct 10 '12 at 20:46