0
#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?

skidog
  • 13
  • 1
  • I think you might want to override the assign operator. – Jack T. Spades May 08 '21 at 20:23
  • Please learn about [the rules of three, five and zero](https://en.cppreference.com/w/cpp/language/rule_of_three). If you want to implement your own explicit memory handling (like you currently do) then you should follow the rule of three or five. But I rather recommend you use `std::vector` and use the rule of zero instead. – Some programmer dude May 08 '21 at 20:28
  • @JackT.Spades -- you **override** a virtual function, by providing a definition in the derived class with the same signature. What's needed here is to **overload** the assignment operator. – Pete Becker May 08 '21 at 20:32
  • @JackT.Spades Thanks for the help. I was conflating the copy constructor and assignment operator as the same thing. – skidog May 08 '21 at 20:41

0 Answers0