Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are C++ arrays copy constructible?

Tags:

c++

Is this code valid in C++?

class MyClass    
{
    public:
    Class2 array [100];
    Myclass (const Myclass& other) : array (other.array) {}
};

If it isn't, what's the best way to achieve the same result?

like image 824
jbgs Avatar asked Nov 30 '22 20:11

jbgs


2 Answers

In C++ arrays are not explicitly copyable (not copy-constructible, not assignable). Your code will not compile.

Yet in C++ arrays become indirectly copyable when wrapped into a class. This means that if you remove your constructor definition, then the implicit copy constructor generated by the compiler for your class MyClass will actually successfully copy the array by some "magical" means that are not available to you directly.

But if for some reason you have to define the copy constructor explicitly, then your options are restricted to leaving the array default-initialized and then explicitly copying the data in the body of the constructor through std::copy or something similar. Or you can simply re-wrap your array, which is actually what the already suggested std::array can do for you.

like image 161
AnT Avatar answered Dec 03 '22 10:12

AnT


Regardless of whether or not this is valid, if all your copy constructor does is to copy the array, then I would rather avoid writing it and let the compiler generate one implicitly.

Also, I would recommend following chris's advice in C++11 and use std::array rather than C-style arrays:

#include <array>

class MyClass
{
public: // In case you really want this to be public
    std::array<Class2, 100> arr;
};

By the way, this would also allow you to initialize you array in the copy constructor's initializer list (but again, do this only if needed):

class MyClass
{
public:
    MyClass() { }
    MyClass (const MyClass& other) : arr(other.arr) {}
//                                   ^^^^^^^^^^^^^^

private:
    std::array<Class2, 100> arr;
};

Here is a live example.

like image 21
Andy Prowl Avatar answered Dec 03 '22 11:12

Andy Prowl