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

return an pointer to an object from a function without using new to allocate the pointer

本文关键字:指针 分配 new 返回 对象 函数      更新时间:2023-10-16

来自线程

我应该在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;
  }
}

这是一个简单的 dequeue() 操作。我的 tmp 是一个本地指针。但我仍然归还它。

感谢马赫什

我在main()中有以下语句

node a8(8); //node constructor with the value

因此,tmp 指向头部指向的内容,并且头部指向不同的节点,如 a8。

由于 a8 在整个 main() 中都有效,tmp 在整个 main() 中也有效

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

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

int* boom()
{
    int sVar = 10;
    int *ptr = &sVar;
    return ptr;
} // life time of sVar ends here

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

函数返回一个本地指针,该指针是全局(或类成员)指针的副本,head 。 它不返回指向局部变量的指针。 还行。

我提供我的意见仅用于讨论。 我使用以下代码返回从外部传入的对象,并且知道该对象可以被此函数销毁。传入的对象可以在本地创建。 通常有一些逻辑可以返回新对象或使用现有对象来提高效率。 有时使用内存总是非常棘手(可能需要几天或更长时间来修复错误)。

Objx* funcAvoidNew(Objx& obj) {
  if (somecondition) {
    return new Objx();
  else {
    Objx* p = new Objx;
    *p = std::move(obj);
    return p;
}