【问题标题】:What is the best way to manage the lifetime of an object variable? [duplicate]管理对象变量生命周期的最佳方法是什么? [复制]
【发布时间】:2012-01-22 14:07:41
【问题描述】:

可能重复:
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 使用更少的内存并更有效地释放双端队列。那是对的吗?它们之间的 [其他] 区别是什么?

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

【问题讨论】:

  • 现在等一下。这两个版本没有做同样的事情。那么,真正的问题是什么?
  • 感谢语法编辑。以正确的方式表达我快疯了。
  • 对你的英语吹毛求疵:“dude”这个词并不意味着问题,它通常意味着朋友。 :-)
  • 是的,对不起。问题或疑问是词。

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


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2011-09-28
    • 1970-01-01
    • 2010-09-10
    • 2013-06-11
    • 2014-11-20
    • 2013-02-27
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    相关资源
    最近更新 更多