<分区>
我想知道为什么当您从函数返回时指向的数据没有立即删除。在下面的代码片段中,我希望当我将 x 的地址返回到函数返回时初始化它的指针时,应该立即删除存储在 x 地址中的数据。但是我仍然能够在 main 中获得正确的值,然后仅在多一行代码之后它突然变成垃圾了吗?为什么这不立即发生
int* function(int x)
{
cout << x << endl; // This outputs 5 as expected
return &x;
}
int main()
{
int* a = function(5);
cout << *a; // This still outputs 5. Why?
cout << endl;
cout << *a; // It is garbage here as expected
cout << endl;
return 0;
}
谢谢