我有如下功能
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/