Chris
Chris

Reputation: 1

Initializing array on stack with copy constructor

I want to have a stack-allocated array initialized by a copy constructor.

I only see methods allocating memory on the heap, or using std::array.

With std::array, it would look like the following:

class A
{
    std::array<int, 5> my_array;    // I would like to have int my_array[5]; instead of the std::array
    int size;
public:
    A(const A& p)
        : my_array{ p.my_array }, size(p.size) {}
}

How can I implement this without std::array<int,5> but with a plain array (int my_array[5];)? I have added this in the comment in the code.

At the moment, the array contains integers. If this would contain, let's say a class B, which contains also a pointer:

class B
{
   int* my_ptr;
}

Does std::array handle this correctly and perform a deep copy?

Upvotes: 0

Views: 192

Answers (1)

eerorika
eerorika

Reputation: 238341

Arrays cannot be copy-initialised in C++. You can either:

  • Assign each member in a loop i.e. std::copy in the constructor body.
  • Or wrap the array inside a class, and use the generated copy constructor. There is a template for such wrapper class in the standard library. It's the std::array that you already know of.

Of course, your class itself is a class that is a wrapper for the array, so you could simply not have user defined copy constructor, and instead use the implicitly generated one:

struct A
{
    int my_array[5];
    int size;
};

If this would contain, let's say a class B which contains also a pointer ... does the std::array handle this correctly

Yes.

... and performs a deep copy?

No. Copying a std::array copies each element and nothing more. Copying a pointer is a shallow copy.

Upvotes: 1

Related Questions