删除由另一个函数返回的指针指向的对象

Delete an object pointed by a pointer returned from another function

本文关键字:指针 对象 返回 另一个 函数 删除      更新时间:2023-10-16

一个例子,

#include<iostream>
using namespace std;
vector<int>* F()
{
    vector<int>*x=new vector<int>(3);
    x[1]=1; x[2]=2; x[3]=3;
    return x;
}

现在我想删除向量或释放另一个函数F1中x指向的内存块,类似于:

bool F1(vector<int>*x)
{
    delete x; 
    return 1;
}

有什么可以实现我想要的吗?

谢谢!

使您的F()功能类似

#include<iostream>
using namespace std;
vector<int> F() {
    vector<int> x;
    x.resize(4);
    x[1]=1; x[2]=2; x[3]=3;
    return x;
}

不需要F1()