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?
Because you allocated using
new[]you should dodelete[] myQueue;in destructor. Otherwise it would invoke undefined behavior. BTW, you can usestd::vector<std::queue<int> >if you don’t want to get this type of memory management issues.