在c++中,Delete指针和重新分配给出了相同的结果
delete pointers and reallocation are giving same result in c++?
我有c++指针删除和重新分配的问题。请给我讲讲这两种方法。我没有机会使用智能指针。(这不是一个实际的代码-我应该用int代替引用类型)
#include <iostream>
#include <queue>
using namespace std;
int main() {
queue<int*>q;
int* a= new int(5);
q.push(a);
/* 1. method */
while (!q.empty()) {
int* x = q.pop();
....do something...
delete x;/* is here deleting the firstly created int a object? */
/* or only deleting newly created allocation of *x? */
}
/* 2. method */
int* x = q.pop();
while (!q.empty()) {
....do something...
*x = q.pop();
}
/* here i'm reallocating the values for x. is here deleting firstly created int a object? */
/* is 2 method = 1 method ? */
return 0;
}
delete x;/* is here deleting the firstly created int a object? */
是的。new
调用分配内存并返回一个指针,您将其压入队列。然后(尝试)将值弹出到x
中。你可以随心所欲地复制指针,但是它们只会被分配和删除一次。
/* or only deleting newly created allocation of *x? */
什么?不。不管你想问什么,答案都是否定的。这个问题很麻烦。
/* here i'm reallocating the values for x. is here deleting firstly created int a object? */
不,你不是在"重新分配x的值"。假设这段代码可以编译(实际上没有),但假设它做了您认为它应该做的事情,那么答案是否定的。你也不能删除"首次创建为一个对象"
发生的情况是,您泄漏了存储在a
中的原始值的内存(随后推入队列),因为您从未删除它。此外,第一次弹出后队列为空,您永远不会进入循环。
但是如果确实进入循环,则会出现类型冲突,此时您将刚刚弹出的指针存储到您最初在a
中分配的整数大小的内存位置,并弹出到x
中。你的编译器应该警告你。
现在让我们假设你说(这里我也向你展示从std::queue
访问和弹出的正确方法):
x = q.front();
q.pop();
现在您仍然泄漏了x
的旧值,因为您没有将其存储在其他地方并且没有删除它。你已经用队列中的下一个值替换了它,你也没有删除它,所以你也可能会泄漏。
/* is 2 method = 1 method ? */
。方法一是最正确的,但是你还是错了。你的意思:
while( !q.empty() )
{
int *x = q.front();
q.pop();
// do something...
delete x;
}
- 如何通过查找迭代器结果分配给一组对的元素
- 分配给浮点数的积分文字除法 - 为什么结果是错误的?
- 分段错误分配函数结果
- 使用动态分配的数组进行矩阵乘法;结果不正确
- 具有预分配结果C++的重载加运算符
- 贪婪地分配分数以最大化最终结果
- Valarray 就地操作作为临时分配给出不同的结果
- 为什么在C 中不确定,为签名类型的对象分配范围的值的结果
- 左col结果分配给相同的矩阵会导致分割故障
- 是否可以为 #define 分配定义的结果?
- 将稀疏 mat-vec-mult 的结果存储到预分配的向量中
- 如何在 c++ 中将 std:fixed << setprecision(5) 的结果分配给变量
- 只有当声明一个对象时,内存空间才会分配给类的数据成员,那么为什么 Sizeof(class_name) 给我结果
- 为什么无法将 std::bind 的结果分配给函数指针
- 为何分配给基本呼叫的结果,为什么不是编译器错误
- 从函数结果中分配 std::shared_ptr 的一行是什么?
- 将函数结果分配给变量的问题
- 在班级中使用动态分配的C风格字符串,并带有复制和分配操作员,给出了意外的结果
- 这将是在将函数分配给变量或一次又一次地调用函数之间使用函数结果的最佳方式
- 特征:如何防止大型对象的额外副本;在RHS上未实现完整矩阵的情况下分配结果