从函数返回指向对象的指针,而不使用 new 分配指针
return an pointer to an object from a function without using new to allocate the pointer
来自线程
我应该在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;
}
相关文章:
- 将指针分配给另一个指针时会发生什么情况?
- C++将一个指针分配给另一个指针时执行的类型检查
- 我似乎无法为指针分配一个数组,然后更改数组的内容
- C++为 void 指针分配一个字符串
- 当我在 C++ 中将派生类的指针分配给指针时,地址会更改
- MPI 集合通信中的指针分配
- 函数指针分配在创建 DLL 后导致错误
- 通过双指针分配指针
- C++编译时使用 constexpr 字符数组指针分配静态数组?
- 我可以直接为指针分配地址吗?如果是,如何做到这一点
- 为什么为char指针分配内存不会截断char序列
- C++指针分配字符数组的地址
- 将 void 指针分配给另一个 void 指针
- 如何将不同的成员函数指针分配给注册类的不同实例?
- 如何为指针分配特定的内存地址?
- C++ - 无法将顶部常量指针分配给另一个非常量指针
- 将指针分配给另一个指针时会发生什么情况?
- 为指向C++中的对象/对象的指针分配堆内存
- 将指针分配给字符串变量中包含的地址
- 当直接分配时,为什么此功能指针分配起作用,而不是与有条件的操作员一起使用