前段時間復習面試的時候,看到這個問題經常有問到,我這個小白就看了些博客和書,總結一下。
new可以說是個一個關鍵字,也可以說是一個運算符,並且可以被重載。
1、new operator
這個就是平時最經常用的new,用法如下程序所示:
1 class A 2 { 3 public: 4 A(int i) :a(i){} 5 private: 6 int a; 7 }; 8 9 int main() 10 { 11 A* example = new A(1); 12 }
new operator實際上執行了以下三個步驟:
1、調用operator new分配內存(后面要說的第二種new),如果類本身定義了operator new,那么會調用類自己的operator new,而不是全局的;
2、調用A的構造函數A::A(int);
3、返回相應的指針
2、operator new
operator new不調用構造函數,而僅僅分配內存,有兩個版本,前者拋出異常,后者當失敗時不拋出異常,而是直接返回:
void* operator new (std::size_t size); void* operator new (std::size_t size, const std::nothrow_t& nothrow_value) noexcept;
可以看到,operator new的作用有點類似與C語言中的malloc,有的地方說operator new的底層實現可以是malloc。
C++中可以用set_new_handler()設置拋出bad_alloc()異常時調用的處理函數,<<Effective C++>>有幾個條款很詳細描述了具體做法。
我還是太菜了,水平不夠,不太能理解自定義異常處理函數的內容...T T
1 class A 2 { 3 public: 4 A(int i) :a(i){} 5 void* operator new(size_t size) 6 { 7 cout << "call A::operator new" << endl; 8 return malloc(size); 9 } 10 void operator delete(void* p) 11 { 12 cout << "call A::operator delete" << endl; 13 return free(p); 14 } 15 void* operator new(size_t size, const nothrow_t& nothrow_value) noexcept 16 { 17 cout << "call A::operator new (noexcept)" << endl; 18 return malloc(size); 19 } 20 void operator delete(void* p, const nothrow_t& nothrow_value) noexcept 21 { 22 cout << "call A::operator delete (noexcept)" << endl; 23 free(p); 24 } 25 private: 26 int a; 27 }; 28 29 int main() 30 { 31 A* example1 = new A(1); 32 delete example1; 33 A* example2 = new(nothrow) A(2); 34 delete example2; 35 }
用一個小例子可以證明一下,確實調用的是自定義operator new/delete,而不是全局的。
3、placement new
placement new僅在一個已經分配好的內存指針上調用構造函數,基本形式如下:
void* operator new (std::size_t size, void* ptr) noexcept;
placement new不需要拋出異常,因為它自身不分配內存。
同時,ptr指針是已經分配好的,可能在棧上也可能在堆上,如下面的例子:
1 class A 2 { 3 public: 4 A(int i) :a(i){} 5 int getValue(){ return a; } 6 private: 7 int a; 8 }; 9 10 int main() 11 { 12 A* p1 = new A(1); //在堆上分配 13 A A2(2); //在棧上分配 14 A* p2 = &A2; 15 cout << "placement new前的值: " << p1->getValue() << " " << p2->getValue() << endl; 16 17 A* p3 = new(p1) A(3); //在p1的位置上構造 18 A* p4 = new(p2) A(4); //在p2的位置上構造 19 cout << "placement new后的值: " << p1->getValue() << " " << p2->getValue() << endl; 20 }
第一次輸出的是1,2;在相應位置構造后,輸出值變為3,4。