返回指针后删除堆

  • 本文关键字:删除 指针 返回 c++
  • 更新时间 :
  • 英文 :


我有一个如下函数

int* readFile(string InputPath)
{
    int *myvar = new int[10]; //The file has 10 lines (Using heap)
    ifstream inFile;
    inFile.open(InputPath.c_str(), ios::in);
    if (inFile.fail())
    {
        cout << "Error reading the input file ";
        cout << InputPath << ".";
        exit(0);
    }
    string fileLine;
    while (getline(inFile, fileLine))
    {
       myvar[i]=toint(fileLine); //will be converted to int!
    }
    ;
    inFile.close();

    return myvar;
}:

如何释放堆 (myvar)?一般来说,返回这种数组的最佳方法是什么?

显然,调用delete[]成为调用者的责任。请注意,这意味着调用方必须知道返回的指针是用 new[] 分配的,这并不完全是最佳的。

您应该返回一个std::vector<int>,这使得一切变得更加简单。

如何释放堆(myvar)?

你返回的 int*;不要改变它,不要丢失它,当你完成记忆时,

delete [] theReturnedPointer;

除非你有很好的理由把它做成一个数组,否则你可以省去内存管理的麻烦,只使用一个向量。

最佳方法

最好的方法是返回一个向量:

vector<int> readFile(const string& InputPath)
{
    ifstream inFile(InputPath); // or inputPath.c_str() for old compilers
    if (!inFile)
    {
        cout << "Error reading the input file " << InputPath << ".";
        exit(0); // thow would be better! Or at least return an empty vector.
    }
    vector<int> myvar;
    for(int n; inFile >> n && myvar.size() < 10; )
    {
       myvar.push_back(n);
    }
    return myvar;
}

但是如果你真的真的想用new[],那么至少返回自我管理的指针,std::unique_ptr<int[]>。永远不要让原始指针转义函数,不要在C++中。

调用方必须delete[]从函数返回的值。目前的代码不为数组末尾以外的写入提供任何保护:

while (getline(inFile, fileLine))
{
    myvar[i]=toint(fileLine); //will be converted to int!
}

但是,由于这C++改用std::vector<int>并直接从输入流中读取int而不是将它们作为字符串读取并执行转换。std::vector<int>将为您处理内存管理:

std::vector<int> myvar;
int i;
while (inFile >> i) myvar.push_back(i);

从函数返回std::vector<int>。调用方可以确切地知道返回值中有多少个int(如果返回数组,除非包含哨兵值来指示结束,否则它就不能这样做),并且不需要显式删除它。

必须有一些代码会在这个指针上调用 delete。

我认为,更好的方法是获取指针作为参数。这样做会迫使使用此函数的人初始化数组,所以他会知道,他将来必须删除它。

C++ 中的约定是不返回分配的内存。相反,函数原型应如下所示

size_t readFile(string InputPath,int* array,size_t n_elements);

该函数返回它实际放置在数组中的元素数。调用方将使用适当的方法分配和释放内存,而不是 new/delete[],而是 malloc/free 或较低级别的系统函数,如 VirtualAlloc。

最新更新