Возникла проблема с моим деконструктором

0

Весь код работает на данный момент минус мой деструктор. Когда я это называю, я получаю сообщение об ошибке "Отладка отладки"!

Строка 52

Выражение: _BLOCK_TYPE_IS_VALID (p_Head-> nBlockUse)

Это для задания, которое должно быть выполнено через час. Я пытаюсь понять это самостоятельно без везения. Это происходит во время выполнения, и после того, как мой процесс завершился и ждет в системе ("ПАУЗА");

#pragma once
#include "stdafx.h"
#include <array>
#include <stdexcept>
#include <iostream>
#include <string>
// class OutOfBoundsException
// Thrown when an input is outside the availabe range of an array.
// Tells the user what the error was, and the offending parameter
class OutOfBoundsException
{
private:
    int m_input;
    std::string m_error;
public:
    OutOfBoundsException(int input)
    {
        m_input = input;
        m_error = "Out of bounds: ";
    }
    int getInput() const
    {
        return m_input;
    }
    std::string getError() const
    {
        return m_error;
    }
};
class MyVector
{
private:
    // create constant of default capacity set to two and a const BLANK for a blank     array
    const int DEFAULT_CAPACITY = 2;
    const int BLANK = 0;
    // create variables to store the current capacity and the current size
    int currentCapacity;
    int currentSize;
    // create a global pointer for the array
    int* myArrayPtr;
public:
    // MyVector()
    // Default Constructor
    // Sets values per default
    MyVector()
    {
        // sets currentCapacity to default capacity
        currentCapacity = DEFAULT_CAPACITY;
        // sets currentSize to blank
        currentSize = BLANK;
        // creates a dynamic array using default parameters above
        myArrayPtr = new int[currentCapacity];
    }

    // MyVector(int n)
    // Constructor that takes an input for the capacity of the array
    MyVector(int n)
    {
        // sets currentCapacity to n
        currentCapacity = n;
        // sets currentSize to blank
        currentSize = BLANK;
        // creates a dynamic array using parameters above
        myArrayPtr = new int[currentCapacity];

    }
    // ~MyVector()
    // Destructor that cleans up memory allocations within class
    ~MyVector()
    {
        // deletes dynamic array
        delete[] myArrayPtr; // the heap is happy
    }
    // size function
    // Purpose: returns the current size of the array
    // Parameters: N/A
    // Returns: currentSize
    int size() const
    {
        // returns the size of the array << currentSize
        return currentSize;
    }
    // capacity function
    // Purpose: returns the current capacity of the array
    // Parameters: N/A
    // Returns: currentCapacity
    int capacity() const
    {
        // returns the current capacity of the array << currentCapacity
        return currentCapacity;
    }
    // clear function
    // Purpose: deconstructs the array, then reconstructs a default array
    // Parameters: N/A
    // Returns: N/A
    void clear()
    {
        // sets all elements back to defaults
        delete[] myArrayPtr;
        currentCapacity = DEFAULT_CAPACITY;
        currentSize = BLANK;
        myArrayPtr = new int[currentCapacity];
    }
    // push_back function
    // Purpose: pushes n into the back of the array, if the array is too small to hold another value, it doubles the size of the array.
    // Parameters: int n
    // Returns: N/A
    void push_back(int n)
    {
        if (currentSize == currentCapacity)
        {
            if (currentCapacity == BLANK)
            {
                clear();
            }
            else
            {
                // create a local array that will be destroyed as soon as
                int* temp = new int[currentCapacity * DEFAULT_CAPACITY];
                for (int i = 0; i < currentCapacity; i++)
                {
                    temp[i] = myArrayPtr[i];
                }
                delete[] myArrayPtr;
                currentCapacity *= DEFAULT_CAPACITY;
                myArrayPtr = temp;
            }
        }
        if (currentSize != BLANK)
        {
            myArrayPtr[currentSize] = n;

        }
        else
        {
            myArrayPtr[currentSize] = n;
        }
        currentSize++;

    }
    // at function
    // Purpose: returns value at n
    // Parameters: int n
    // Returns: myArrayPtr[n]
    // Throws OutOfBoundsException if n is greater than the index of the last item in the array
    int at(int n) const
    {
        try
        {
            // returns the value at n
            if (n > currentSize - 1)
                throw OutOfBoundsException(n);
            else
                return myArrayPtr[n];
        }
        catch (OutOfBoundsException e)
        {
            std::cout << std::endl << e.getError() << e.getInput() << std::endl;
        }
        return myArrayPtr[n];
    }
};

Код, вызывающий эту ошибку, представляет собой простой класс runner, созданный с единственной целью его тестирования.

#pragma once
#include "stdafx.h"
#include "MyVector.h"
#include <iostream>
using namespace std;
int main()
{
MyVector hello(10);
// hello.~MyVector();


hello.push_back(-1);
hello.push_back(-1);
hello.push_back(-1);
hello.push_back(-1);
hello.push_back(0);

hello.~MyVector();
system("PAUSE");
return 0;
}
  • 0
    Пожалуйста, опубликуйте код, который вызывает, использует этот код, возможно, вы удаляете указатель дважды.
Показать ещё 4 комментария
Теги:
exception
runtime-error
destructor

2 ответа

0

Деструктор называется дважды. hello.~MyVector() - первый. :-)

0

Объект MyVector не выделяется самостоятельно, поэтому программа позаботится об автоматическом удалении. Если вы хотите удалить его, просто выделите его следующим образом:

MyVector    *mv = new Myvector(...);

[...]
delete mv;
return ;

delete автоматически вызовет деструктор объекта.

Кстати, http://www.cplusplus.com/articles/y8hv0pDG/

Coplien - это путь, даже когда вы им не нужны, придерживайтесь привычки, чтобы всегда определять их.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню