When should I allocate on the heap? (C++)

I don't really understand when I should be allocating memory on the heap and when I should allocate on the stack. All I really know is that allocating on the stack is faster, but since the stack is smaller I shouldn't use it to allocate large data structures; what other things should I take into account when deciding where to allocate memory? Edit: where should I allocate instance variables?


  • Allocate on the stack for most objects. Lifetime == scope.
  • If you need to control manually the lifetime of the object, allocate it on the heap.
  • If the object is big and the stack is not big enough for it, allocate it on the heap.
  • Use the (badly names) RAII idiom in cases 2 and 3, it allow you to use object on the stack that manipulate resources that might be your objects on the heap -- a good example are the smart pointers like std::shared_ptr/boost::shared_ptr.

  • 当内存必须超出当前函数的范围时才使用堆。


    You can only use the stack as storage space when you know at compile time how big the storage you are going to need is. It follows that you can use the stack for

  • Single objects (like you do declare a local int or double or MyClass temp1; variable
  • statically-sized arrays (like you do when you declare char local_buf[100]; or MyDecimal numbers[10];
  • You have to use the heap ("free store") when you only know how much space you need at runtime and you should probably use the heap for large statically known buffers (like don't do char large_buf[32*1024*1024]; )

    Normally however, you very seldomly should touch the heap directly, but normally use objects that manage some heap memory for you (and the object possibly lives on the stack or as member of another object - where you then don't care where the other object lives)

    To give some example code:

    {
    char locBuf[100]; // 100 character buffer on the stack
    std::string s;    // the object s will live on the stack
    myReadLine(locBuf, 100); // copies 100 input bytes to the buffer on the stack
    s = myReadLine2();
      // at this point, s, the object, is living on the stack - however 
      // inside s there is a pointer to some heap allocated storage where it
      // saved the return data from myReadLine2().
    }
    // <- here locBuf and s go out-of-scope, which automatically "frees" all
    //  memory they used. In the case of locBuf it is a noop and in the case of
    //  s the dtor of s will be called which in turn will release (via delete)
    //  the internal buffer s used.
    

    So to give a short answer to your question when : Don't allocate anything on the heap (via new ) unless this is done via an appropriate wrapper object. (std::string, std::vector, etc.)

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

    上一篇: 我该如何重载新操作符才能在堆栈上分配?

    下一篇: 我应该在什么时候分配堆? (C ++)