c++ - 返回指针后删除堆

标签 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>相反,这让一切变得如此简单。

关于c++ - 返回指针后删除堆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12490284/

相关文章:

c++ - 请求从 'int' 到非标量类型 'Point"的转换

c++ - 为什么容器节点不能在wxDataViewCtrl中有多个列

c++ - 指针取消引用 : actual mechanism of compiler

字符类的 C++ 继承

c++ - Printf 行为和转换

c++ - 导出的 DLL 函数未按词法排序?

c++ - Visual Studio Express 2010 C++ 反汇编调试

java - 将数据存储到 Cassandra 时是大端还是小端?

c++ - c++ 中字符串的动态构造 - 什么是更 c++-ish 的方法来做到这一点?

c# - 在实例类中包装静态非托管库