在 C++ 中使用 delete 運算子

Jinku Hu 2023年1月30日 2021年4月29日
  1. 使用 delete 運算子釋放物件的已分配資源
  2. 使用 delete 運算子釋放向量中的元素
在 C++ 中使用 delete 運算子

本文將說明在 C++ 中如何使用 delete 運算子的幾種方法。

使用 delete 運算子釋放物件的已分配資源

使用 new 運算子動態分配的物件應在程式退出之前釋放,這意味著呼叫方負責顯式呼叫 delete 操作。請注意,可以使用建構函式初始化程式使用 new 運算子宣告和初始化物件。下面的示例程式碼演示了這種情況,然後在從 main 函式返回之前釋放相應的資源。注意不要在堆物件上呼叫 delete 運算子會導致記憶體洩漏,從而導致長時間執行的程序佔用大量記憶體。

#include <iostream>
#include <vector>
#include <iomanip>
#include <random>
#include <cstdlib>

using std::cout; using std::vector;
using std::endl; using std::setw;
using std::string;

int main()
{
    int *num = new int(1024);
    auto *sp = new string(10, 'a');

    cout << *num << endl;
    cout << *sp << endl;

    for (const auto &item : *vp) {
        cout << item << ", ";
    }
    cout << endl;

    delete num;
    delete sp;

    return EXIT_SUCCESS;
}

輸出:

1024
aaaaaaaaaa

newdelete 運算子也可以與標準庫容器一起使用。即,在以下示例程式碼中的單個語句中分配和初始化了 std::vector 物件。一旦 new 運算子返回指向 vector 的指標,我們就可以像常規的 vector 物件一樣對其進行操作。

#include <iostream>
#include <vector>
#include <iomanip>
#include <random>
#include <cstdlib>

using std::cout; using std::vector;
using std::endl; using std::setw;

int main()
{
    auto *vp = new vector<int>{0,1,2,3,4,5,6,7,8,9};

    for (const auto &item : *vp) {
        cout << item << ", ";
    }
    cout << endl;

    delete vp;

    return EXIT_SUCCESS;
}

輸出:

0, 1, 2, 3, 4, 5, 6, 7, 8, 9,

使用 delete 運算子釋放向量中的元素

delete 運算子與動態分配的陣列一起使用會略有不同。通常,newdelete 一次對一個物件進行操作,但是陣列需要通過一次呼叫分配多個元素。因此,方括號表示法用於指定陣列中元素的數量,如以下示例程式碼所示。這樣的分配返回指向第一個元素的指標,可以將其取消引用以訪問不同的成員。最後,當不需要陣列時,應使用特殊的刪除符號將其釋放,該符號包含空方括號,以確保每個元素都已被釋放。

#include <iostream>
#include <vector>
#include <iomanip>
#include <random>
#include <cstdlib>

using std::cout; using std::vector;
using std::endl; using std::setw;

constexpr int SIZE = 10;
constexpr int MIN = 1;
constexpr int MAX = 1000;

void initPrintIntVector(int *arr, const int &size)
{
    std::random_device rd;
    std::default_random_engine eng(rd());
    std::uniform_int_distribution<int> distr(MIN, MAX);

    for(int i = 0; i < size; ++i) {
        arr[i] = distr(eng) % MAX;
        cout << setw(3) << arr[i] << "; ";
    }
    cout << endl;
}

int main()
{
    int *arr1 = new int[SIZE];

    initPrintIntVector(arr1, SIZE);

    delete [] arr1;
    return EXIT_SUCCESS;
}

輸出:

311; 468; 678; 688; 468; 214; 487; 619; 464; 734;
266; 320; 571; 231; 195; 873; 645; 981; 261; 243;
Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn

相關文章 - C++ Memory