shen shen - 3 years ago 115
C++ Question

[c++]Missing of destructor

when I declare a new queue object like that, the exe stop working:

arrayQueue myQueue;
myQueue.enqueue("111");
char* x=myQueue.dequeue();
cout<<x<<endl;


when I create the object using new, it works:

arrayQueue* myQueue=new arrayQueue();
myQueue->enqueue("111");
char* x=myQueue->dequeue();
cout<<x<<endl;


so what's the problem? the following code is a "queue" I wrote:

in .h head file:

class arrayQueue{
private:
array<char*,100> queueContrainer;
int maxSize;
int head;
int tail;
public:
arrayQueue();
~arrayQueue();
bool isEmpty();
bool isFull();
int getSize();
void enqueue(char*);
char* dequeue();
};


implementation in .cpp(only upload the constructor here:

arrayQueue::arrayQueue(){
head=0;
tail=0;
maxSize=100;
for(array<char*,100>::iterator it1=queueContrainer.begin();it1!=queueContrainer.end();++it1){
*it1="Empty";
}
}


main.cpp; arrayQueue.cpp; arrayQueue.h. three files to compile:


https://drive.google.com/file/d/0B5FCKG1I8ce0R1RORUFYWFhUN0E/edit?usp=sharing

https://drive.google.com/file/d/0B5FCKG1I8ce0QlBCTzdBUlJfZG8/edit?usp=sharing

https://drive.google.com/file/d/0B5FCKG1I8ce0SGdWOVg1RzNTNW8/edit?usp=sharing

Answer Source

Do you have a valid destructor? In the second example the object pointed to by myQueue is not deleted as it should, and the destructor never gets called.

In the first example myQueue is deleted when it goes out of scope, and the destructor will be called automatically. If your destructour is missing or buggy, the program will fail to compile or run.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download