Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Using C++ arrays with <code>new</code> (that is, using dynamical arrays) should be avoided. There is the problem you have to keep track of the size, and you need to delete them manually, and do all sort of housekeeping. </p> <p>Using arrays on the stack is also discouraged because you don't have range checking, and passing the array around will lose any information about its size (array to pointer conversion). You should use <code>boost::array</code> in that case, which wraps a C++ array in a small class and provides a <code>size</code> function and iterators to iterate over it.</p> <p>Now the <strong>std::vector vs. native C++ arrays</strong> (taken from the internet):</p> <pre><code>// Comparison of assembly code generated for basic indexing, dereferencing, // and increment operations on vectors and arrays/pointers. // Assembly code was generated by gcc 4.1.0 invoked with g++ -O3 -S on a // x86_64-suse-linux machine. #include &lt;vector&gt; struct S { int padding; std::vector&lt;int&gt; v; int * p; std::vector&lt;int&gt;::iterator i; }; int pointer_index (S &amp; s) { return s.p[3]; } // movq 32(%rdi), %rax // movl 12(%rax), %eax // ret int vector_index (S &amp; s) { return s.v[3]; } // movq 8(%rdi), %rax // movl 12(%rax), %eax // ret // Conclusion: Indexing a vector is the same damn thing as indexing a pointer. int pointer_deref (S &amp; s) { return *s.p; } // movq 32(%rdi), %rax // movl (%rax), %eax // ret int iterator_deref (S &amp; s) { return *s.i; } // movq 40(%rdi), %rax // movl (%rax), %eax // ret // Conclusion: Dereferencing a vector iterator is the same damn thing // as dereferencing a pointer. void pointer_increment (S &amp; s) { ++s.p; } // addq $4, 32(%rdi) // ret void iterator_increment (S &amp; s) { ++s.i; } // addq $4, 40(%rdi) // ret // Conclusion: Incrementing a vector iterator is the same damn thing as // incrementing a pointer. </code></pre> <p>Note: If you allocate arrays with <code>new</code> and allocate non-class objects (like plain <code>int</code>) or classes without a user defined constructor <em>and</em> you don't want to have your elements initialized initially, using <code>new</code>-allocated arrays can have performance advantages because <code>std::vector</code> initializes all elements to default values (0 for int, for example) on construction (credits to @bernie for remembering me). </p>
 

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