从函数返回指向对象的指针,而不使用new来分配指针

cxf*_*f54 2 c++ new-operator

从线程中

我什么时候应该在C++中使用new关键字?

答案讨论了如果需要从函数返回指向对象的指针,必须使用"new"来创建指向对象的指针.

但是,我的代码工作正常.我使用本地指针而不是为新指针分配一些内存.

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;
  }
}
Run Code Online (Sandbox Code Playgroud)

这是一个简单的dequeue()操作.我的tmp是一个本地指针.但我还是回来了.

感谢Mahesh

我在main()中有以下语句

node a8(8); //node constructor with the value
Run Code Online (Sandbox Code Playgroud)

因此tmp指向head指向的内容,并指向不同的节点,如a8.

由于a8在main()中有效,因此tmp在main()中也是有效的

Mah*_*esh 6

程序工作正常,因为tmp生命周期指向的内存位置超出了dequeue成员函数的范围.tmp它位于堆栈上,它的生命周期结束时函数返回,但它指向的内存位置并非如此.

相比之下,这段代码并不安全:

int* boom()
{
    int sVar = 10;
    int *ptr = &sVar;

    return ptr;
} // life time of sVar ends here
Run Code Online (Sandbox Code Playgroud)

ptr指向的内存位置在函数返回之前有效(但不会在返回之后).