C++ New::operator new



在C++中,可以使用new關鍵字在執行時動態分配RAM堆段中的記憶體。在宣告時,會傳遞一個指定分配記憶體大小的引數。可以使用new運算子為預設和唯一的資料型別分配記憶體。

函式運算子new分配原始記憶體,在概念上與malloc()相同。

  • 它是覆蓋預設堆分配邏輯的機制。
  • operator new也可以在全域性或特定類中過載。

語法

以下是C++ New::operator new的語法:

void* operator new (std::size_t size) throw (std::bad_alloc);       (throwing allocation)
void* operator new (std::size_t size, const std::nothrow_t& nothrow_value) throw();                (nothrow allocation)
void* operator new (std::size_t size, void* ptr) throw(); 

引數

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

示例1

讓我們看一下下面的例子,我們將使用operator new並獲取輸出。

#include <cstdio>
#include <cstdlib>
#include <new>
void* operator new(std::size_t sz) {
   std::printf(" new(size_t), size = %zu\n", sz);
   if (sz == 1)
      ++sz;
   if (void *ptr = std::malloc(sz))
      return ptr;
   throw std::bad_alloc{};
}
int main() {
   int* p1 = new int;
   delete p1;
}

輸出

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

 new(size_t), size = 4

示例2

讓我們看一下另一種情況,我們將使用operator new。

#include <iostream>
#include <new>
struct MyClass {
   int data[100];
   MyClass() {
      std::cout << "It constructed [" << this << "]\n";
   }
};
int main () {
   std::cout << "1: ";
   MyClass * p1 = new MyClass;
   std::cout << "2: ";
   MyClass * p2 = new (std::nothrow) MyClass;
   std::cout << "3: ";
   new (p2) MyClass;
   MyClass * p3 = (MyClass*) ::operator new (sizeof(MyClass));
   delete p1;
   delete p2;
   delete p3;
   return 0;
}

輸出

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

1: It constructed [0x5596f5df72c0]
2: It constructed [0x5596f5df7460]
3: It constructed [0x5596f5df7460]

示例3

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

#include<iostream>
#include<stdlib.h>
using namespace std;
class car {
   string name;
   int num;
   public:
   car(string a, int n) {
      cout << "TutorialsPoint" << endl;
      this->name = a;
      this->num = n;
   }
   void display() {
      cout << "Name: " << name << endl;
      cout << "Num: " << num << endl;
   }
   void *operator new(size_t size) {
      cout << "Welcome" << endl;
      void *p = malloc(size);
      return p;
   }
};
int main() {
   car *p = new car("RX100", 2011);
   p->display();
   delete p;
}

輸出

當代碼執行時,它將生成如下輸出:

Welcome
TutorialsPoint
Name: RX100
Num: 2011
廣告