2011-12-17 50 views
1

可能重複:
When should I use the new keyword in C++?管理對象變量生存期的最佳方法是什麼?

我不是一個專業的程序員,我只有經驗與小項目的工作,所以我有一個小麻煩了解什麼是怎麼回事。

我通常使用class_name var_name創建對象。但是現在我正在'學習'Objective-C,幾乎所有的東西都是一個指針,並且你對內存使用有更多的控制。

現在我創建一個包含無限循環的應用程序。

我的問題是,哪個選項是一個更好的方式來管理內存使用(導致更少的內存使用)?

  1. 一個正常的聲明(對我來說)

    #include <stdio.h> 
    #include <iostream> 
    #include <deque> 
    
    using namespace std; 
    
    class myclass 
    { 
        public: 
        int a; 
        float b; 
        deque<int> array; 
    
        myclass() {cout <<"myclass constructed\n";} 
        ~myclass() {cout <<"myclass destroyed\n";} 
        //Other methods 
        int suma(); 
        int resta(); 
    }; 
    
    int main(int argc, char** argv) 
    { 
        myclass hola; 
    
        for(1) 
        { 
         // Work with object hola. 
         hola.a = 1; 
        } 
    
        return 0; 
    } 
    
  2. 使用newdelete

    #include <stdio.h> 
    #include <iostream> 
    #include <deque> 
    
    using namespace std; 
    
    class myclass 
    { 
        public: 
        int a; 
        float b; 
        deque<int> array; 
    
        myclass() {cout <<"myclass constructed\n";} 
        ~myclass() {cout <<"myclass destroyed\n";} 
        //Other methods 
        int suma(); 
        int resta(); 
    }; 
    
    int main(int argc, char** argv) 
    { 
        myclass hola; 
    
        for(1) 
        { 
          myclass *hola; 
          hola = new myclass; 
    
         // Work with object hola. 
         hola->a = 1; 
    
         delete hola; 
        } 
    
        return 0; 
    } 
    

我認爲選擇2使用更少的內存,更有效地釋放了雙端隊列。那是對的嗎?他們之間有什麼[其他]差異?

我真的很困惑在哪裏使用每個選項。

+0

現在持有。這兩個版本並沒有做同樣的事情。那麼,真正的問題是什麼? – 2011-12-17 11:47:46

+0

感謝您的語法編輯。我瘋狂地把它放在正確的方式。 – 2011-12-17 11:48:51

+1

Nitpick on your English:「夥計」一詞並不意味着問題,它通常意味着一個朋友。 :-) – 2011-12-17 11:52:26

回答

1

使用第一個選項。第一個選項在本地存儲中創建對象實例,而第二個選項在免費商店(a.k.a堆​​)上創建它。在堆上創建對象比本地存儲更「昂貴」。

總是儘量避免在C++中儘量使用new

對這個問題的答案是一個很好看的:In C++, why should new be used as little as possible?

相關問題