What is the best way to manage the lifetime of an object variable?

Possible Duplicate:
When should I use the new keyword in C++?

I'm not a professional programmer and I only have experience working with small projects, so I'm having a little trouble understanding what's going on here.

I usually create objects using class_name var_name . But now I'm 'learning' Objective-C, where almost everything is a pointer and you have more control over memory usage.

Now I'm creating an application which contains an infinite loop.

My question is, which option is a better way to manage memory usage (resulting in less memory usage)?

  • A normal declaration (for me)

    #include <stdio.h>
    #include <iostream>
    #include <deque>
    
    using namespace std;
    
    class myclass 
    {
      public:
        int a;
        float b;
        deque<int> array;
    
      myclass() {cout <<"myclass constructedn";}
      ~myclass() {cout <<"myclass destroyedn";}
      //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;
    }
    
  • Using new and delete

    #include <stdio.h>
    #include <iostream>
    #include <deque>
    
    using namespace std;
    
    class myclass 
    {
      public:
        int a;
        float b;
        deque<int> array;
    
      myclass() {cout <<"myclass constructedn";}
      ~myclass() {cout <<"myclass destroyedn";}
      //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;
    }
    
  • I think option 2 uses less memory and frees the deque more efficiently. Is that correct? What are the [other] differences between them?

    I'm really confused about where to use each option.


    Use the first option. The first option creates the object instance in local storage, while the second option creates it on the free store (aka the heap). Creating objects on the heap is more "expensive" than in local storage.

    Always try to avoid using new in C++ as much as you can.

    The answers to this question are a good read: In C++, why should new be used as little as possible?

    链接地址: http://www.djcxy.com/p/96534.html

    上一篇: C ++中变量初始化的区别

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