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

标签 c++ new-operator

来自线程中

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/

相关文章:

java/c++ 输出如何工作? cout<< 系统输出打印

c++ - 在混合的 C 和 C++ 代码中使用 operator new

c++ - 在类(class)特定版本的 placement new 中做什么?

c++ - 如何在QSortFilterProxyModel中重新排序/移动项目?

c# - "new"关键字在 C# 中有什么作用,为什么它在不使用时只是一个警告?

javascript - 奇怪的 Javascript 'new' 形式

c++ - 重载 operator new

C++ 遍历某个子类的列表

c++ - 从 map 中删除/删除对象时调用析构函数

c++ - 在指针场景中使用 std::shared_ptr