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
while(!myqueue->empty())
{
myqueue->pop();
}
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.
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 (withnew) allocated objects, that’s done by invokingdelete: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:
(Note that
std::queuewill 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.