2011-12-17 28 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?

相关问题