删除队列对象的数组 [英] Delete an array of queue objects

查看:113
本文介绍了删除队列对象的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的工作包含队列与未决定,直到构造被称为数组长度的数组对象上。基本上,它看起来像下面这样

I am working on an object that contains an array of queues with an array length that isn't decided until the constructor is called. Basically it looks something like the following

#include <queue>

class myClass{
public:
  //public functions
private:
  //private functions and variables

  queue<int>* myQueue;
};

它被初始化像这样:

it is initialized like so:

myClass::myClass(int numOfQueues){
  myQueue = new queue<int>[numOfQueues];
}

这一切精美的作品,看起来。它的功能完全像我希望的那样,但现在我每次退出程序时,我得到一个分段错误。这个类中有一些其他的阵列被以同样的方式初始化,但这些类型的布尔 INT 而不是队列。我的析构函数如下:

This all works beautifully, it seems. it functions exactly like I was hoping it would, but now every time I exit the program I get a segmentation fault. The class has some other arrays in it that are initialized in the same way, but those are of types bool and int instead of queue. My destructor looks like:

myClass::~myClass(){
  delete boolArray;
  delete intArray;
  delete myQueue;
}

现在我认为这析构函数工作的 boolArray intArray 指针,因为我没有开始得到段错误,直到我加入 myQueue中。没有任何人有任何想法的正确方法是编写析构函数?难道这是我必须做的,析构函数只是未在适当的时候叫什么?

Now I assume this destructor is working for the boolArray and intArray pointers, because I didn't start to get a segfault until I added myQueue. Does anyone have any idea what the proper way is to write the destructor? Is it possible that this is all I have to do and the destructor just isn't being called at the proper time?

推荐答案

由于您分配使用新[] 你应该做的删除[] myQueue中; 的析构函数。否则,将调用未定义的行为。顺便说一句,你可以使用的std ::矢量&lt;的std ::队列&LT; INT&GT;方式&gt; 如果你不希望得到这种类型的内存管理问题

Because you allocated using new[] you should do delete[] myQueue; in destructor. Otherwise it would invoke undefined behavior. BTW, you can use std::vector<std::queue<int> > if you don't want to get this type of memory management issues.

这篇关于删除队列对象的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆