管理对象变量生命周期的最佳方法是什么?

时间:2011-12-17 11:42:39

标签: c++ objective-c memory-management

  

可能重复:
  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;
    }
    
  3. 我认为选项2使用更少的内存并更有效地释放双端队列。那是对的吗?它们之间的[其他]差异是什么?

    我真的很困惑在哪里使用每个选项。

1 个答案:

答案 0 :(得分:1)

使用第一个选项。第一个选项在本地存储中创建对象实例,而第二个选项在免费存储(a.k.a堆​​)上创建它。在堆上创建对象比在本地存储中“更昂贵”。

始终尽量避免在C ++中使用new

这个问题的答案是一个很好的解读: In C++, why should new be used as little as possible?