dimanche 27 septembre 2020

Vector.exe has triggered a breakpoint. CRT Detected. Heap Corruption Detected. Operator Assign not working properly

enter image description here

Vector.exe has triggered a breakpoint. enter image description here

Vector.h

#ifndef VECTOR_H

#include <cassert>
#include <cstring>

#include <iterator>
#include <initializer_list>

class Vector
{
public:
    Vector() : _capacity(1)
    {
        nums = new int[_capacity];
        validate();
    }

    Vector(std::initializer_list<int> numbers) 
        : _capacity(numbers.size())
    {
        nums = new int[_capacity];
        for(const int& i: numbers)
        {
            push_back(i);
        }

        validate();
    }

    virtual ~Vector()
    {
        validate();
        delete[] nums;
    }

    int size() const {
        return _size;
    }

    int capacity() const {
        return _capacity;
    }

    int* data() {
        return nums;
    }

    const int* data() const {
        return nums;
    }
    
    void push_back(int i) {
        if (_size >= _capacity)
            _capacity = _capacity * 2;

        nums[_size] = i;
        _size++;
        validate();
    }

    int& operator[](int i)
    {
        return nums[i];
    }

    const int& operator[](int i) const
    {
        return nums[i];
    }

    Vector& operator=(const Vector& v)
    {
        if (this == &v) return *this;

        delete[] nums;

        _capacity = v.capacity();
        _size = v.size();

        nums = new int[_capacity];
        std::memcpy(nums, v.data(), _capacity);

        return *this;
    }

protected:

    inline void validate() 
    {
        assert(_size <= _capacity);
    }

private:

    int* nums = nullptr;
    int _capacity = 0;
    int _size = 0;
};

#endif // !VECTOR_H

main.cpp

#include <algorithm>
#include <iostream>
#include "vector.h"

int main()
{
    Vector v1 = {0, 1, 2, 3, 4, 5, 6};
    Vector v2 = v1;

    for (int i = 0; i < v2.capacity(); ++i)
    {
        std::cout << v2[i] << std::endl;
    }

    return 0;
}

I am NOT sure, what's wrong with my operator= implementation. I want to be able to assign, and be able to delete the other object, and still be able to preserve, and delete the current object. I believe my operator= is correctly implemented, but not sure where it breaks exactly. I am unable to trace at the moment.

Aucun commentaire:

Enregistrer un commentaire