删除在不同函数中动态分配的对象时崩溃

Crash when deleting an object allocated dynamically in a different function

本文关键字:对象 崩溃 动态分配 函数 删除      更新时间:2023-10-16

我写了一个简单的程序:

#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

但是请不要尝试在生产代码中做这种事情。