Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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

like image 527
WriteBackCMO Avatar asked Oct 29 '25 17:10

WriteBackCMO


2 Answers

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).

like image 145
Mahesh Avatar answered Oct 31 '25 06:10

Mahesh


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.

like image 31
Jonathan Leffler Avatar answered Oct 31 '25 07:10

Jonathan Leffler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!