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

bhu*_*hni -1 c++ new-operator delete-operator heap-corruption

我写了一个简单的程序:

#include<iostream>
#include<list>
using namespace std;
list<int>& func();

int main(){
    list<int> a = func();
    delete &a;
    std::cout<<"Here\n";
}

list<int>& func(){
    list<int>* ptr = new list<int>;
    return *ptr;
}
Run Code Online (Sandbox Code Playgroud)

这个程序永远不会打印Here到cout流....

它只是崩溃..

我无法找到原因..

Luc*_*ore 6

我猜你的意思是:

list<int> a = func();
Run Code Online (Sandbox Code Playgroud)

因为否则它甚至不会编译.无论如何,变量a从未被分配过new.它是返回引用的变量的副本func.

虽然您返回一个引用,但您复制它是因为a它本身不是引用.以下将有效:

list<int>& a = func();
delete &a;
Run Code Online (Sandbox Code Playgroud)

崩溃:http: //ideone.com/T3Iew

作品:http: //ideone.com/ONVKU

无论如何,我希望这是出于教育目的(这很酷,因为你可以理解角落案例),但对于生产代码来说,这将是非常错误的.