模板类析构函数崩溃程序中的动态数组

时间:2014-02-16 22:54:07

标签: c++ templates destructor dynamic-arrays

我有一个模板类,其中包含模板类型的私有动态数组。在main中,我有一个while循环,它根据用户输入的初始条件继续,这一切都正常(从整个时间读取/操作数组)。

然后在while循环结束后,不再使用该数组。但我的程序仍然执行我的最后2个couts和文本文件写入,然后运行一个简单的lambda函数(它不使用数组或其类),但在完成之前崩溃:

newFile.close();
return 0;

这实际上并没有带走任何功能,但我无法弄清楚为什么它崩溃而不是只是结束,根据调试器,程序计数器在数组的析构函数结束处停止。

我的queueType.h:

template<class Type>
class QueueType {
public:
    QueueType();
    ~QueueType();
    QueueType(const QueueType& other);
    Type& getFront() {return queueArray[front];}
    void reposition();
    void addElement(Type);
    bool isEmpty() const {return numElements == 0;}
    bool isFull() const {return SIZE == numElements;}
    void updateWaitTimes(Type*&, int&, int&);

    QueueType<Type>& operator=(const QueueType other);

    friend void swap(QueueType& first, QueueType& second) {
        using std::swap;
        swap(first.front, second.front);
        swap(first.back, second.back);
        swap(first.numElements, second.numElements);
        swap(first.queueArray, second.queueArray);
    }
private:
    static const int SIZE = 25;
    int front, back, numElements;
    Type *queueArray;
};

我也在这个类中实现了3的规则(加上构造函数),如下所示:

template<class Type>
QueueType<Type>::QueueType() {
    queueArray = new Type[SIZE];
    front = back = numElements = 0;
}

template<class Type>
QueueType<Type>::~QueueType() {
    delete [] queueArray;
}

template<class Type>
QueueType<Type>::QueueType(const QueueType& other) {
    front = other.front;
    back = other.back;
    numElements = other.numElements;
    std::copy(other.queueArray, other.queueArray + SIZE, queueArray);
}

template<class Type>
QueueType<Type>& QueueType<Type>::operator=(const QueueType other) {
    swap(*this, other);
    return *this;
}

使用这个主要:

typedef void(*Action)();
void iterateQueue(Action action) {
    action();
}

int main(int argc, char** argv) {
    QueueType<CustomerType> Line;
        while (... < ...) {
            //various functions operate on Line, which produce no problems
        }
    cout << ...
    newFile << ...
    iterateQueue([] () {cout << endl << "I'm a lambda function!" << endl;});
    cout << "this never prints";
    return 0;
}

编辑代码已添加

1 个答案:

答案 0 :(得分:1)

您的复制构造函数错误:

template<class Type>
QueueType<Type>::QueueType(const QueueType& other) {
    front = other.front;
    back = other.back;
    numElements = other.numElements;
    std::copy(other.queueArray, other.queueArray + SIZE, queueArray);
}

您没有为当前对象分配queueArray。试试这个:

 template<class Type>
 QueueType<Type>::QueueType(const QueueType& other) : 
                            queueArray(new Type[SIZE]),
                            front(other.front), 
                            back(other.back), 
                            numElements(other.numElements)


{
    std::copy(other.queueArray, other.queueArray + SIZE, queueArray);
}