【发布时间】:2014-03-16 02:07:57
【问题描述】:
我有一个模板类,其中包含模板类型的私有动态数组。在 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;
}
编辑:添加代码
【问题讨论】:
-
请提供代码,而不是描述您的代码 扩展英语。
-
我展示了我的析构函数代码和 main 中剩余的未运行代码,不知道还有什么需要展示这个问题 =/
-
您应该发布一个重现问题的最小样本。否则,唯一的答案是“您的代码中有错误”。
-
您的复制构造函数完全损坏了。请不要使用
new和delete,除非您是专家。请改用适当的动态容器。 -
嗯,我从一篇关于 3 o_O 修复技巧规则的文章中获得了复制/分配设置?不知何故,它在 NetBeans 上编译得很好,只是在运行后崩溃
标签: c++ templates destructor dynamic-arrays