C++ New::operator delete[]



C++ New::operator delete[]是一個常規函式,可以像其他任何函式一樣顯式呼叫。使用delete[]運算子時,表示式首先呼叫陣列中每個元素的相關解構函式(如果它們是類型別),然後呼叫陣列釋放函式。

名為operator delete[]的成員函式執行類物件的陣列釋放。全域性函式operator delete[]用於所有其他情況。當delete[]語句前面帶有作用域運算子時,只考慮全域性陣列釋放函式。

語法

以下是C++ New::operator delete[]的語法:

void operator delete[] (void* ptr) throw();    (ordinary delete)
void operator delete[] (void* ptr, const std::nothrow_t& nothrow_constant) throw();     (ordinary delete)
void operator delete[] (void* ptr, void* voidptr2) throw();            (placement delete)

引數

  • size - 包含請求的記憶體塊的大小(以位元組為單位)。
  • nothrow_value - 包含常量nothrow。
  • ptr - 指向已分配的適當大小的記憶體塊的指標。
  • voidptr2 - 一個void指標。

示例1

讓我們來看下面的例子,我們將使用operator delete[]並獲取輸出。

#include <iostream>
using namespace std;
struct C {
   C() {
      cout << "Welcome" << endl;
   }
   ~C() {
      cout << "TP" << endl;
   }
};
int main() {
   C *p = new C;
   cout << "pass" << endl;
   delete[] p;
   return 0;
}

輸出

讓我們編譯並執行上面的程式,這將產生以下結果:

Welcome
pass
TP
TP
TP
TP
TP
........

示例2

讓我們來看另一個場景,我們將使用operator delete[]。

#include <iostream>
using namespace std;
int main() {
   int *p = new int;
   cout << "Welcome To World" << endl;
   delete[] p;
   return 0;
}

輸出

執行上面的程式碼後,它將顯示如下輸出:

Welcome To World

示例3

考慮以下情況,我們將檢查operator delete[]的功能。

#include <cstdio>
#include <cstdlib>
#include <new>
void operator delete[](void* ptr) noexcept {
   std::puts("TutorialsPoint");
   std::free(ptr);
}
int main() {
   int* p2 = new int[10];
   delete[] p2;
}

輸出

程式碼執行後,將生成如下所示的輸出:

TutorialsPoint

示例4

讓我們考慮另一個例子,我們將使用operator delete[]並獲取輸出。

#include <iostream>
struct MyClass {
   MyClass() {
      std::cout <<"MyClass is constructed\n";
   }
   ~MyClass() {
      std::cout <<"MyClass is destroyed\n";
   }
};
int main () {
   MyClass * pt;
   pt = new MyClass[3];
   delete[] pt;
   return 0;
}

輸出

程式碼執行後,將生成如下所示的輸出:

MyClass is constructed
MyClass is constructed
MyClass is constructed
MyClass is destroyed
MyClass is destroyed
MyClass is destroyed
廣告
© . All rights reserved.