Delete an array of queue objects

倾然丶 夕夏残阳落幕 提交于 2019-12-12 19:17:53

问题


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?


回答1:


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.




回答2:


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

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




回答3:


Using delete with new[] won't just cause memory leak but also invokes Undefined behaviour.

The correct form of delete to be used with new[] is delete[].

However in idiomatic C++ it is always recommended to use std::vector instead of using C style arrays. You need not explicitly manage memory yourself when you use STL containers.




回答4:


Naveen has already solved the problem. I'd like to add a good programming practice.

The following use case below will also create deletion problems.

void foo()
{
    myClass a;
    myClass b(a);
}

when we declare a, a new instance of myQueue will be created. However when declaring b, copy constructor will be called instead of myClass::myClass(int numQueues) constructor. Thus a.myQueue == b.myQueue.

When exiting function foo, a's destructor will delete myQueue then b's destructor will try to delete an unreferenced pointer which would lead to a fatal error.

A good programming practice is to either implement copy constructor and = operator accordingly or to declare copy constructor and = operator private to avoid such problems.

private:
    myClass(const myClass&);
    const myClass& operator=(const myClass&);

See also boost::NonCopyable



来源:https://stackoverflow.com/questions/5388373/delete-an-array-of-queue-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!