Are C ++ scripts copied?

Is this code valid in C ++?

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

If this is not the best way to achieve the same result?

+4
source share
2 answers

Regardless of whether or not this is true, if all your copy constructors are designed to copy an array, then I would prefer not to write it and let the compiler generate it implicitly.

Also, I recommend following the chris tip in C ++ 11 and using std::array instead of 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 will also allow you to initialize your array in the list of initializers of the copy constructor (but again, do this only if necessary):

 class MyClass { public: MyClass() { } MyClass (const MyClass& other) : arr(other.arr) {} // ^^^^^^^^^^^^^^ private: std::array<Class2, 100> arr; }; 

Here is a living example .

+8
source

In C ++ arrays, they are not explicitly copied (not copied, not assigned). Your code will not compile.

However, in C ++, arrays become indirect when copied to a class. This means that if you delete the constructor definition, then the implicit copy constructor generated by the compiler for your MyClass class will actually successfully copy the array with some magic means that are not available to you directly.

But if for some reason you have to explicitly define the copy constructor, then your parameters are limited by the fact that you leave the default initialized array and then explicitly copy the data in the constructor body via std::copy or something like that. Or you can just flip the array, which actually already suggested std::array can do for you.

+10
source

Source: https://habr.com/ru/post/1490164/


All Articles