james james - 5 months ago 33
C++ Question

how to destroy stl Queue created on heap?

As per req i have to create stl queue on heap
i have created stl queue on heap in constructor of my class as per below code

queue<int> *myqueue;
myqueue=new queue<int>();

Now in destructor i want to destroy it:
so i have written code


please tell me is it right way to destroy it or there is any other mean to avoid memory leak .Please note that
delete myqueue is giving segmentation fault.

sbi sbi

All STL containers have a member clear() that can be used to erase their content. All STL containers will call this member in their destructor, so you won't have to do it manually. So all you have to do is to ensure that the queue itself is destroyed. for dynamically (with new) allocated objects, that's done by invoking delete: delete myqueue;.

That said: I find it dubious that you would want to create a queue dynamically, instead of making it an ordinary class member:

class myclass {
  // whatever
  std::queue<int> myqueue_;

(Note that std::queue will always allocate memory for its content dynamically, even if the queue itself is not dynamically allocated.)

If you have to absolutely create the queue dynamically, make sure you're following the Rule of Three. The crash you describe is what might happen when you copy around classes with dynamically allocated objects that don't have a copy constructor/assignment operator.