簡體   English   中英

返回指針后刪除堆

[英]delete heap after returning pointer

我有一個功能如下

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)? 一般來說,返回此類數組的最佳方法是什么?

如何釋放堆(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[]顯然是調用者的責任。 請注意,這意味着調用者必須知道返回的指針是用new[]分配的,這並不完全是最佳的。

你應該返回一個std::vector<int> ,這使得它變得更加簡單。

調用者必須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 s(如果您返回數組,則無法知道,除非您包含一個指示結束的標記值)並且不需要顯式刪除它。

必須有一些代碼會在這個指針上調用刪除。

我認為,更好的方法是獲取一個指針作為參數。 這樣做會迫使某人使用此函數初始化數組,因此他會知道,他將來必須刪除它。

C++ 中的約定是不返回分配的內存。 相反,函數原型應該看起來像

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

該函數返回它實際放置在數組中的元素數。 調用者將使用適當的方法分配和釋放內存,不是必要的 new/delete[] 而是 malloc/free 或較低級別的系統函數,例如 VirtualAlloc。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM