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.
Credit to Mahesh
I have following statements in the main()
node a8(8); //node constructor with the value
Therefore tmp points to what head points to, and head points to different nodes like a8.
Since a8 is valid throughout the main(), tmp is valid throughout the main() as well
Program works fine because the memory location pointed by tmp lifetime is beyond the scope the dequeue member function. tmp lies on stack and it's life time end as the function returns but it is not the case with the memory location it was pointing to.
By contrast, this code is not safe:
int* boom()
{
int sVar = 10;
int *ptr = &sVar;
return ptr;
} // life time of sVar ends here
The memory location ptr points to is valid until the function returns (but not after it returns).
The function returns a local pointer which is a copy of a global (or class member) pointer, head. It is not returning a pointer to a local variable. It is OK.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With