[C++基礎]033_深入C++的new


1. New的本質

使用關字new在堆上動態創建一個,它實際上做了三件事

    ① 得一內存空

    ② 調構造函數

    ③ 返回指向地址的正確指

如果建的是簡單類型的量,第二步就不執行了。下面我們看一段代碼:

 1 #include <iostream>
 2 using namespace std;
 3 
 4 class A {
 5     int m_value;
 6 public:
 7     A(int value) :m_value(value * value){}
 8     void Func(){
 9         printf("m_value=%d\n", m_value);
10     }
11 };
12 
13 int main()
14 {
15     A *aPtr = new A(1);
16     delete *aPtr;
17     system("pause");
18     return 0;
19 }

在調用 “A *a = new A(1);” 時,其過程大致如下:

1     A *aPtr = (A*)malloc(sizeof(A)); // 分配內存區域
2     aPtr->A::A(1);                   // 調用對象構造函數
3     return aPtr;                     // 返回內存地址指針

上面三句話表面上看起來是得到了aPtr這個指向內存的指針。但是它與new自身的區別在於,當malloc失敗的時候,上面的代碼不會調用分配內存失敗處理程序new_handler。而使用new的話就會。因此,我們要盡可能的使用new,避免一些不必要的麻煩。

下面是 “A *a = new A(1);” 的匯編碼(windows 7, Visual Studio 2008):

 1     A *aPtr = new A(1);
 2 0116140D  push        4    
 3 0116140F  call operator new (1161190h) 
 4 01161414  add         esp,4 
 5 01161417  mov         dword ptr [ebp-0ECh],eax 
 6 0116141D  mov         dword ptr [ebp-4],0 
 7 01161424  cmp         dword ptr [ebp-0ECh],0 
 8 0116142B  je          main+72h (1161442h) 
 9 0116142D  push        1    
10 0116142F  mov         ecx,dword ptr [ebp-0ECh] 
11 01161435  call        A::A (1161019h) 
12 0116143A  mov         dword ptr [ebp-100h],eax 
13 01161440  jmp         main+7Ch (116144Ch) 
14 01161442  mov         dword ptr [ebp-100h],0 
15 0116144C  mov         eax,dword ptr [ebp-100h] 
16 01161452  mov         dword ptr [ebp-0F8h],eax 
17 01161458  mov         dword ptr [ebp-4],0FFFFFFFFh 
18 0116145F  mov         ecx,dword ptr [ebp-0F8h] 
19 01161465  mov         dword ptr [ebp-14h],ecx 

可以看出,在編譯成匯編碼的時候,也是先用new創建一塊內存,接着調用A的構造函數初始化,最后返回內存地址的指針。下面的代碼是微軟對new的實現:

 1 void *__CRTDECL operator new(size_t size) _THROW1(_STD bad_alloc)
 2         {       // try to allocate size bytes
 3         void *p;
 4         while ((p = malloc(size)) == 0)
 5                 if (_callnewh(size) == 0)
 6                 {       // report no memory
 7                 static const std::bad_alloc nomem;
 8                 _RAISE(nomem);
 9                 }
10 
11         return (p);
12         }

可以看到,它也是調用了malloc函數,但是還有一些其他的處理,這就是new比malloc稍微復雜,安全的原因。

:不同編譯器的實現也是不同的,這里只是分析了微軟對new的實現,至於g++及其他的實現,還未及分析。

2. New的分類

我們經常使用的new都是“new operator”和“new expression”,但事實上C++中提到的new,至少可能代表以下三種含義:new operator、operator new、placement new。

   ①.new operator:    我們平時使用的new,其行為如前所述的三步,事實上我們是不能更改它的行為的。

   ②.operator new:    從匯編碼可以看出來,new operator的第一步是通過operator new完成的。這里的new就相當於一個運算符號,是可以重載的。它默認調用分配內存的代碼,嘗試得到一塊堆上的內存空間,成功就返回;失敗則調用new_handler。

■上面說到,operator new是可以重載的,下面就讓我們來重載operator new試試看(嚴格術語上來說,應該是覆蓋),我們把類A這樣定義:

 1 class A {
 2     int m_value;
 3 public:
 4     A(int value) :m_value(value * value){}
 5 
 6     void Func(){
 7         printf("m_value=%d\n", m_value);
 8     }
 9 
10  void* operator new(size_t size){ 11         printf("operator new called\n"); 12         return ::operator new(size); 13  } 14 };

        然后執行 “A *a = new A(1);” 時,可以看到在Console里輸出了一句"operator new called",這說明operator new已經被我們重載了。這樣我們就可以在分配內存前做一些我們想做的事,比如檢測環境等等。

        ※:   "::operator new(size)" 這句話的作用是調用全局的operator new,因為分配內存的操作我們一般是不用重載的。

■上面提到了全局的operator new,一般不重載,那么全局的operator new能不能被重載呢?答案是,可以。下面就讓我們來重載全局的operator new來看看(嚴格術語上來說,應該是覆蓋),在全局領域處插入如下代碼:

1 void* operator new(size_t size) 
2 { 
3   printf("global new\n"); 
4   return malloc(size); 
5 } 

再次執行代碼 “A *a = new A(1);” 可以看到,字符串"global new"被輸出了。說明全局的operator new已經被我們重載了。當然,實際應用場景並不需要我們做這么復雜的操作。

上面我們說到過“當malloc失敗的時候,上面的代碼不會調用分配內存失敗處理程序new_handler”,你可能會想自己定義new_handler的處理代碼,事實上它是可以重載的,下面我們來重載試試看(嚴格術語上來說,應該是覆蓋):

 1 #include <iostream>
 2 using namespace std;
 3 
 4 class A {
 5     int m_value;
 6     static new_handler    current_handler;
 7 public:
 8     static new_handler set_new_handler(new_handler p){
 9         new_handler old_handler = current_handler; //保存傳入的Handler,返回以前的Handler
10         current_handler = p;
11         return old_handler;
12     }
13 
14     void* operator new(size_t size){
15         new_handler globe_handler = std::set_new_handler(current_handler); // 調用全局函數set_new_handler設置handler
16 
17         void *memory = NULL;
18         try{
19             memory = ::operator new(size); 20         }catch(std::bad_alloc){
21             std::set_new_handler(globe_handler);
22             throw;
23         }
24         std::set_new_handler(globe_handler);
25 
26         return memory;
27     }
28 
29     A(int value) :m_value(value * value){}
30 };
31 new_handler A::current_handler = NULL;
32 
33 void handlerFunc(){
34     cout<<"Bad Memory."<<endl;
35 }
36 
37 int main()
38 {
39     A::set_new_handler(handlerFunc);
40     A *aPtr = new A(1);
41 
42     delete aPtr;
43     system("pause");
44     return 0;
45 }

程序編譯之后調試,可以看到我們的程序是可以捕獲到着色代碼行的異常的。這樣就可以定義我們自己的異常處理函數了,比如銷毀之前申請的資源等等。

    ③. placement new:  它的功能就相當於我們平常使用的new的本質代碼的第二步——調用構造函數。下面看看它的使用方法。

 1 #include <iostream>
 2 using namespace std;
 3 
 4 class A {
 5     int m_value;
 6 public:
 7     void* operator new(size_t size){
 8         cout<<"operator new."<<endl;
 9         void* memory = NULL;
10         memory = malloc(size);
11         return memory;
12     }
13     A(int value) :m_value(value * value){}
14 };
15 
16 int main()
17 {
18     A *aPtr = new A(1); 19     ::new(aPtr) A(1); 20 
21     delete aPtr;
22     system("pause");
23     return 0;
24 }

上面着色代碼的第二行就是placement new的使用方法,在該行斷點后,按F11,可以看到它調用的代碼,如下:

1 inline void *__CRTDECL operator new(size_t, void *_Where) _THROW0()
2     {    // construct array with placement at _Where
3     return (_Where);
4     }

可以看到它與operator new的實現之間的區別,placement new有兩個參數,一個傳入大小,一個傳入地址。而operator new的實現只有一個參數,即需要分配內存的大小。

3. 總結

    ①. C++的new有三重含義:new operator、operator new、placement new。

    ②. new operator是我們經常使用的new,它的內部相當於實現了三步操作:分配內存、調用構造函數、返回地址指針。

    ③. operator new可以看做運算符,可以重載,重載它可以做內存分配前后的一些工作。

    ④. placement new就是調用構造函數,它的書寫方式比較特別:“::new(aPtr) A(1)

 

 參考文檔

     http://wenku.baidu.com/view/30709e12a21614791711284b.html

     http://wenku.baidu.com/view/6b75ac81e53a580216fcfe6c.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM