删除在不同函数中动态分配的对象时崩溃
Crash when deleting an object allocated dynamically in a different function
我写了一个简单的程序:
#include<iostream>
#include<list>
using namespace std;
list<int>& func();
int main(){
list<int> a = func();
delete &a;
std::cout<<"Heren";
}
list<int>& func(){
list<int>* ptr = new list<int>;
return *ptr;
}
该程序永远不会将Here
打印到cout流中。
它只是崩溃..
我找不到原因..
我假设你的意思是:
list<int> a = func();
因为否则它甚至无法编译。无论如何,变量a
从未与new
一起分配。它是 func
返回所引用的变量的副本。
尽管返回引用,但会复制它a
因为它本身不是引用。以下方法将起作用:
list<int>& a = func();
delete &a;
崩溃:http://ideone.com/T3Iew
作品:http://ideone.com/ONVKU
无论如何,我希望这是出于教育目的(这很酷,因为您可以了解极端情况),但对于生产代码,这将是非常非常错误的。
因为你有一个声明为指针,而不是引用。将list<int>* a
更改为list<int> & a
。
但是请不要尝试在生产代码中做这种事情。
相关文章:
- 类对象数组的问题会导致崩溃
- 在虚幻引擎中删除NXOpen对象时崩溃
- 将方法转换为调用该方法的成员函子对象会导致崩溃
- 将对象创建为全局/静态对象会崩溃,而本地对象不会崩溃
- C 回调函数在对象 pascal 上崩溃
- 在 C++ 中,类实例对象 do memcpy 总是崩溃
- 具有重载类型转换运算符的函数对象崩溃
- 当删除上下文属性中的QLIST对象时,QT QML应用程序崩溃
- 全局范围内的对象会导致程序退出时崩溃
- 我的视频流程在运行darknet.exe以进行检测对象时崩溃了
- 为什么通过引用传递从 std::function 派生的对象会使程序崩溃?
- 使用指针的矢量矩阵在对象上调用析构函数时程序崩溃
- 使用全局对象时崩溃,但使用本地对象时不会崩溃
- QT应用程序声明新对象后崩溃
- 将对象指针的push_back崩溃到std :: vector中
- 将对象写入文件时应用程序崩溃
- 创建对象数组c++时崩溃
- 在小对象优化中调试崩溃以进行类型擦除
- 为什么将对象从一个智能指针移至另一个原因崩溃
- 应用程序与使用C++中的Luabind在循环中创建的对象崩溃