我的功能如下
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)? 一般来说,返回这种数组的最佳方法是什么?
答案 0 :(得分:2)
如何释放堆(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 ++。
答案 1 :(得分:2)
调用者明显有责任在其上调用delete[]
。请注意,这意味着调用者必须知道返回的指针是使用new[]
分配的,这不是最佳选择。
你应该返回一个std::vector<int>
,这样就可以更简单了。
答案 2 :(得分:2)
调用者必须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
(除非你包含一个指示结尾的sentinel值,否则它不能返回数组)并且不需要显式删除它。
答案 3 :(得分:1)
必须有一些代码会在此指针上调用delete。
我认为,更好的方法是将指针作为参数。 这样做会强迫有人使用这个函数初始化数组,所以他知道,他将来必须删除它。
答案 4 :(得分:0)
C ++中的约定是不返回已分配的内存。相反,函数原型应该看起来像
size_t readFile(string InputPath,int* array,size_t n_elements);
该函数返回它实际放置在数组中的元素数。调用者将使用适当的方法分配和释放内存,而不是nessecary new / delete [],而是malloc / free或更低级别的系统函数,如VirtualAlloc。