jeudi 15 avril 2021

Returned value gets deleted before its assigned to a variable

I have a class that represents an N-dimensional array. The problem I've run into is this:

If I try to assign negated values from arr2 to arr, operator- is called, correct value gets returned, but before its assigned to arr a destructor gets called on the returned object and deletes it.

int main() {
    ...
    Array<int> arr(5);
    Array<int> arr2(5);

    arr2.fillRandPositive(20);

    try {
        arr = -arr2;    

        cout << arr << endl;
        cout << arr2 << endl;
    } ...
    Array<T> operator-() const {
        if (!(std::is_arithmetic_v<T> && typeid(T).hash_code() != typeid(char).hash_code())) 
            throw "\nIt's impossible to negate array of this type.";

        Array<T> temp(*this);

        for (size_t i = 0; i < numOfCells; i++) 
            temp.ArrCell(i) = -Arr[i];
        
        return temp;
    }
    template<typename U>
    Array<T>& operator=(const Array<U>& set) {
        if (!(typeid(T).hash_code() == typeid(U).hash_code()) &&
            !(std::is_arithmetic_v<T> && std::is_arithmetic_v<U>)) throw "Values can't be assigned.";
        
        if (Arr != nullptr) delete[] Arr;
        
        //..copy dimensions and allocate memory..//

        for (size_t i = 0; i < numOfCells; i++) 
            Arr[i] = (T)set.ArrCell(i);
        
        return *this;
    }

I've been looking for an answer on google, but I couldn't find anything useful because I don't know how to properly word the question. If any of you know what Im doing wrong, I would appreciate the help.

Console output:

Arr

 -572662307 -572662307 -572662307 -572662307 -572662307

Arr2

     1     8     0     3    16

Received Error:

HEAP[Projekt6.exe]: Invalid address specified to RtlValidateHeap( 007B0000, 007B5688 )

Aucun commentaire:

Enregistrer un commentaire