Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can only use the stack as storage space when you know <em>at compile time</em> how big the storage you are going to need is. It follows that you can use the stack for</p> <ul> <li>Single objects (like you do declare a local <code>int</code> or <code>double</code> or <code>MyClass temp1;</code> variable</li> <li>statically-sized arrays (like you do when you declare <code>char local_buf[100];</code> or <code>MyDecimal numbers[10];</code></li> </ul> <p>You <em>have to</em> use the heap ("free store") when you only know how much space you need at runtime and you <em>should</em> probably use the heap for large statically known buffers (like <strong>don't</strong> do <code>char large_buf[32*1024*1024];</code> )</p> <p>Normally however, <em>you</em> 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)</p> <p>To give some example code:</p> <pre><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(). } // &lt;- 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. </code></pre> <p>So to give a short answer to your question <strong>when</strong>: <em>Don't</em> allocate anything on the heap (via <code>new</code>) unless this is done via an appropriate wrapper object. (std::string, std::vector, etc.)</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload