像这样在作用域外使用delete是不正确的吗
Is it incorrect to use delete out of scope like this?
int* func()
{
int* i=new int[3];
return i;
}
void funcc()
{
int* tmp=func();
//delete allocated memory after use
delete[] tmp;
}
我的观点是,编译器在编译funcc时无法知道有3 int要删除,例如,如果func在另一个文件中。
这在C++FAQ lite:中有介绍
[16.14]在p=new Fred[n]之后,编译器如何知道有n删除[]p期间要销毁的对象
简言之:魔术。
长答案:运行时系统存储对象的数量n,如果你只知道指针p,它就可以被检索到。有两种流行的技术可以做到这一点。这两种技术由商业级编译器使用,两者都有折衷,并且两者都不完美。这些技术是:
- 过度分配数组,并将n放在第一个Fred对象的左侧
- 使用以p为键、n为值的关联数组
这就是delete
的使用方式,很好。数组大小存储在幕后的某个位置,因此delete[]
无论在哪里发生都会做正确的事情。
然而,像这样处理指针很容易出错:在删除数组之前很容易丢失指针,或者逻辑变得如此复杂,以至于你最终删除了同一个数组两次。你最好使用一个类来为你管理阵列:
#include <vector>
std::vector<int> func() {
return std::vector<int>(3);
}
void funcc() {
auto tmp = func();
// no need to do anything - the vector frees its memory automatically
}
相关文章:
- 使用2个键的cpp-stl::优先级队列排序不正确
- 正弦级数方程计算不正确
- 我试图制作一个程序,要求用户输入问题和答案,但程序循环不正确
- 密码登录程序将永远循环并显示不正确的结果
- 在C++中返回不正确的楼层函数值
- 形状对象的旋转和缩放不正确C++
- C++ 读取文件读取文件不正确
- 关于类的 Python 文档 - 对C++的引用不正确
- 特征 LLT 模块给出不正确的结果?
- glibcxx STL 在实现 std::valarray::sum() 时是否不正确?
- 如果语句逻辑不正确
- 来自逆 vp 矩阵和相机位置的光线方向不正确
- 不正确的操作数类型 MSVC
- 数组填充了不正确的值
- 我是否不正确地集中了这些字符数组?
- 为什么除非我使用 cout,否则我的值不正确?
- 计算幂级数的数学结果不正确
- 为什么 sizeof 在 C++ 中给出不正确的字节数?
- atoi() 在应用于大型命令行参数时会产生不正确的值
- 像这样在作用域外使用delete是不正确的吗