来自线程中
When should I use the new keyword in C++?
答案谈到如果您需要从函数返回指向对象的指针,则何时必须使用“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 是本地指针。但我还是返回了。
归功于 Mahesh
我在 main() 中有以下语句
node a8(8); //node constructor with the value
因此tmp指向head指向的东西,head指向不同的节点,比如a8。
因为 a8 在整个 main() 中有效,所以 tmp 在整个 main() 中也有效
最佳答案
程序运行良好,因为 tmp
生命周期指向的内存位置超出了 dequeue 成员函数的范围。 tmp
位于堆栈上,它的生命周期在函数返回时结束,但它指向的内存位置并非如此。
相比之下,这段代码并不安全:
int* boom()
{
int sVar = 10;
int *ptr = &sVar;
return ptr;
} // life time of sVar ends here
ptr
指向的内存位置在函数返回之前有效(但在返回之后无效)。
关于c++ - 从函数返回指向对象的指针,而不使用 new 分配指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18710613/