Itachi Uchiwa
Itachi Uchiwa

Reputation: 3164

How to copy a built-in array via copy-constructor?

We know that a built-in array can neither be copied nor be assigned. So If it is a member data of a class/struct/union It is OK to leave the compiler do its magic to copy them:

struct ArrInt5{
    ArrInt5() = default;
    ArrInt5(ArrInt5 const&) = default; // OK 
    int a[5];
};

ArrInt5 a, b = a; // OK

Upvotes: 0

Views: 1301

Answers (1)

Bitwize
Bitwize

Reputation: 11220

The only way to generate this effect for you automatically is to wrap your array in a class type of some kind that has a compiler-generated copy constructor (e.g. such as a defaulted constructor). In your particular example, you could just have Foo(const Foo&) be defaulted:

struct Foo{
    Foo();
    Foo(Foo const&) = default;
    // This generates your:
    // "Foo::Foo(Foo const& rhs) : arr_{rhs.arr_[0], rhs.arr_[1], rhs.arr_[2], rhs.arr_[3], rhs.arr_[4]}"
    // by the compiler

    Bar arr_[5];
};

However the above only works if your copy-logic is trivial. For more complex copying, you can't always have a default copy constructor -- but we can solve this more generally.

If you wrap an array data member of any type/size in a struct or class and make sure it has compiler-generated copy constructors, then copying is easy in a constructor.

For example:

template <typename T, std::size_t N>
struct Array {
  ...
  T data[N];
};

This allows for the simple case of copying:

Array<Bar,1000000> a = {{...}};
Array<Bar,1000000> b = a; 

Or the more complex case of copying in a constructor that might require more logic than the compiler-generated ones:

class Foo {
  ...
  Foo(const Foo& other);
  ...
  Array<Bar,100000> arr_;
};

Foo::Foo(const Foo& other)
  : arr_{other.arr_}
{
  ... other complex copy logic ...
}

At which point, congratulations -- you have invented std::array! std::array was added to the standard library exactly because it was this simple to introduce a library-solution to this problem without having to alter the language itself. Don't shy away from it.

Upvotes: 5

Related Questions