Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Even though both methods allocates dynamic memory, one is an object made for handling data of arbitrary length (<code>std::vector&lt;T&gt;</code>), while the other is just a pointer to a sequential line of memory slots of size <code>N</code> (<code>int</code>s in this case).</p> <hr> <p><strong>Among other differences</strong></p> <ul> <li><p>A <code>std::vector&lt;T&gt;</code> will automatically resize the allocated memory for your data if you try to append a new value and it runs out of space. A <code>int *</code> will not.</p></li> <li><p>A <code>std::vector&lt;T&gt;</code> will free the allocated memory when the vector goes out of scope, a <code>int *</code> will not.</p></li> <li><p>A <code>int *</code> will have little to no overhead (compared to the vector), though <code>std::vector&lt;T&gt;</code> isn't exactly a new thing and is normally very optimized. Your bottle neck will probably be elsewhere. </p> <p>But a <code>std::vector&lt;int&gt;</code> will always consume more memory than a <code>int *</code>, and some operations will always take a little more time.</p> <p>So if there are memory/CPU limitations and you want to shave off every single cycle that you possible can.. use an <code>int *</code>.</p></li> </ul> <hr> <p><strong>There are situations where one is definitely preferable over the other!</strong></p> <ul> <li><p>When you need "raw"/"real" memory and <strong>full control</strong> over it, <code>operator new</code> is your best bet. </p> <p>For example when you are using <a href="http://www.parashift.com/c++-faq-lite/dtors.html#faq-11.10" rel="nofollow"><code>placement new</code></a>.</p> <p><sup><em>by raw/real memory I mean something that is not managed through a wrapper-container, such as <code>std::vector&lt;T&gt;</code>.</em></sup></p></li> <li><p>When you are looking for a container to handle arbitrary and don't want to reinvent the wheel regarding memory management; <code>std::vector&lt;T&gt;</code> (or any other appropriate STL container) </p></li> </ul>
    singulars
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      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