#include <iostream>
class MyArray {
public:
MyArray(int* array, int size) {
this->size = size;
this->array = new int[size];
for(int i = 0; i < size; i++) {
this->array[i] = array[i];
}
}
MyArray(const MyArray& myArray) {
std::cout << "copying: ";
myArray.print();
std::cout << std::endl;
size = myArray.size;
this->array = new int[size];
for(int i = 0; i < size; i++) {
array[i] = myArray.array[i];
}
}
~MyArray() {
std::cout << "destroying: ";
print();
std::cout << std::endl;
delete []array;
}
const void print() const{
for(int i = 0; i < size; i++) {
std::cout << array[i];
}
}
int* array;
int size;
};
int main() {
int array1[4] = {1, 2, 3, 4};
int array2[4] = {2, 3, 4, 5};
MyArray myArray1(array1, 4);
MyArray myArray2(array2, 4);
MyArray myArray3 = myArray1;
myArray1 = myArray2;
}
In the sample above, I can copy an object into a new variable, myArray3, and the copy constructor prints "copying: 1234" as it should. When I copy myArray2 into the previously initialized myArray1, the copy constructor does not print (possibly due to some kind of Copy Elision). When the destructor is called after the variable goes out of scope, I get a malloc error for deleting the same variable twice. Is there a clean way to copy over an already initialized object variable (myArray1 = myArray2) without running into this issue with the destructor?