Optimization of raw new[]/delete[] vs std::vector
<p>Let's mess around with very basic dynamically allocated memory. We take a vector of 3, set its elements and return the sum of the vector.</p>

<p>In the first test case I used a raw pointer with <code>new[]</code>/<code>delete[]</code>. In the second I used <code>std::vector</code>:</p>

<pre><code>#include &lt;vector&gt;   

int main()
{
  //int *v = new int[3];        // (1)
  auto v = std::vector&lt;int&gt;(3); // (2)


  for (int i = 0; i &lt; 3; ++i)
    v[i] = i + 1;

  int s = 0;
  for (int i = 0; i &lt; 3; ++i)
    s += v[i];

  //delete[] v;                 // (1)
  return s;
}
</code></pre>

<p>Assembly of (1) (<code>new[]</code>/<code>delete[]</code>)</p>

<pre><code>main:                                   # @main
        mov     eax, 6
        ret
</code></pre>

<p>Assembly of (2) (<code>std::vector</code>)</p>

<pre><code>main:                                   # @main
        push    rax
        mov     edi, 12
        call    operator new(unsigned long)
        mov     qword ptr [rax], 0
        movabs  rcx, 8589934593
        mov     qword ptr [rax], rcx
        mov     dword ptr [rax + 8], 3
        test    rax, rax
        je      .LBB0_2
        mov     rdi, rax
        call    operator delete(void*)
.LBB0_2:                                # %std::vector&lt;int, std::allocator&lt;int&gt; &gt;::~vector() [clone .exit]
        mov     eax, 6
        pop     rdx
        ret
</code></pre>

<p>Both outputs taken from <a href="https://gcc.godbolt.org/" rel="noreferrer">https://gcc.godbolt.org/</a> with <code>-std=c++14 -O3</code></p>

<p>In both versions the returned value is computed at compile time so we see just <code>mov eax, 6; ret</code>.</p>

<p>With the raw <code>new[]</code>/<code>delete[]</code> the dynamic allocation was completely removed. With <code>std::vector</code> however, the memory is allocated, set and freed.</p>

<p>This happens <strong>even with an unused variable</strong> <code>auto v = std::vector&lt;int&gt;(3)</code>: call to <code>new</code>, memory is set and then call to <code>delete</code>.</p>

<p>I realize this is most likely a near impossible answer to give, but maybe someone has some insights and some interesting answers might pop out.</p>

<p><strong>What are the contributing factors that don't allow compiler optimizations to remove the memory allocation in the <code>std::vector</code> case, like in the raw memory allocation case?</strong></p>