return an pointer to an object from a function without using new to
allocate the pointer
From the thread in
When should I use the new keyword in C++?
The answer talks about when "new" must be used in order to create a
pointer to an object if you need to return the pointer to the object from
the function.
However, my code below works fine. I use a local pointer instead of
allocating some memory to a new pointer.
node* queue::dequeue(){
if(head==0){
cout<<"error: the queue is empty, can't dequeue.\n";
return 0;
}
else if(head->next !=0){
node *tmp=head;
head=head->next;
tmp->next=0;
return tmp;
}
else if(head->next ==0){
node *tmp=head;
head=0;
tmp->next=0;
return tmp;
}
}
It is a simple dequeue() operation. My tmp is a local pointer. But i still
return it.
No comments:
Post a Comment