从线程中
如果您需要从函数返回指向对象的指针,则答案谈到何时必须使用“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;
}
}
这是一个简单的 dequeue() 操作。我的 tmp 是一个本地指针。但我还是退货了。
归功于马赫什
我在 main() 中有以下语句
node a8(8); //node constructor with the value
因此 tmp 指向 head 指向的内容,而 head 指向不同的节点,如 a8。
由于 a8 在整个 main() 中有效,因此 tmp 在整个 main() 中也有效
原文由 WriteBackCMO 发布,翻译遵循 CC BY-SA 4.0 许可协议
程序运行良好,因为
tmp
生命周期指向的内存位置超出了出队成员函数的范围。tmp
位于堆栈上,随着函数返回,它的生命周期结束,但它指向的内存位置并非如此。相比之下,这段代码并不安全:
内存位置
ptr
指向的内存位置在函数返回之前是有效的(但不是在它返回之后)。