Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete an array of queue objects

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];
}

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;
}

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?

like image 690
Alex Avatar asked Dec 07 '25 04:12

Alex


2 Answers

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.

like image 103
Naveen Avatar answered Dec 08 '25 16:12

Naveen


Why're you not using std::vector instead of arrays?

You need to delete[] arrays, not delete - you allocated with new[]

like image 21
Erik Avatar answered Dec 08 '25 16:12

Erik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!